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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.