0
votes

I am trying to gradient shade under a density plot in R, using ggplot2. I keep getting the density plot, but no shading.

library(quantmod)
library(ggplot2)
library(ggfortify)

getSymbols('XLE')
energy <- coredata(Delt(XLE$XLE.Adjusted, k = 1)["2018-03-08::"])
ggplot(energy, aes(energy)) +
    geom_density(aes(x = energy, fill = energy))+
    scale_fill_gradient2( energy ,
        low = "darkred", high = "navy", mid = "orange", midpoint = 0)

This yields a curve with no fill at all.

Here is a similar example with reproducible data:

test.data <- data.frame(exp(runif(1000,0,1)))

ggplot(test.data, aes(test.data))+
    geom_density(aes(fill = test.data)) +
    scale_fill_gradient(test.data, low = "navy", high = "red")

which yields

enter image description here

1
idownvotedbecau.se/nomcve Can you reproduce this with a subset of data that you can share with us? - Calum You
Okay, I have updated the original question to include an example with reproducible data. - fjparker
I have no idea how your example produced the graph since the code has several errors, including not supplying x aesthetic to geom_density, and supplying data objects rather than colulmn names to aes. I also don't understand what the desired result is - how do you want this to be filled? the fill aesthetic is discrete for geom_density. In your original code, if you set x and fill to the same continuous variable fill would do nothing, and it's unclear what you would be expecting it to do. please look at the examples: ggplot2.tidyverse.org/reference/geom_density.html - Calum You
Simplest solution would be: draw histogram under the density and color it according x-axis values - pogibas
I'm trying to link the color of the fill under the curve with the value of the x-axis. Rather than one fill color, I would like the color to change from "navy" to "darkred". - fjparker

1 Answers

0
votes

Okay, I spent the weekend looking into this, and I finally came up with the answer for shading under a density plot relative to the x-axis in R.

Let's set some reproducible data:

input = runif(1000, 0, 1)
output = exp(input) + cos(input)

Then we need to add a faux-factor, "name", in a data frame:

name = rep("name", length(output))
data.df = data.frame(input, output, name)
data.df$name = as.factor(data.frame$name)

From here, we can use the ggplot2 and ggridges library:

library(ggplot2)
library(ggridges)

ggplot( data.df, aes(x=output, y=name, fill=..x..))+
geom_density_ridges_gradient()+
scale_fill_gradient(low="red4", high="navy")+
ylab(" ")

Which yields: this plot