I have a dataframe df
:
set.seed(3467)
df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))
I wish to create a ridge plot like so:
ggplot(df, aes(x = beta, y = method, color = method, fill = method)) +
geom_density_ridges(size=1)+
scale_fill_manual(values = c("#228b2250", "#0072B250", "#483d8b50")) +
scale_color_manual(values = c("#228b22", "#0072B2", "#483d8b"), guide = "none") +
stat_density_ridges(quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=1)
I wish to add a shaded rectangle like so:
ggplot(df) +
geom_rect(data = data.frame(x = 1),
xmin = -1, xmax = 1, ymin = -Inf, ymax = Inf,
alpha = 0.5, fill = "gray") +
geom_density_ridges2(aes(x = beta, fill = method, y = method))
However, this attempt is unsuccessful:
ggplot(df, aes(x = beta, y = method, color = method, fill = method)) +
geom_density_ridges(size=1)+
scale_fill_manual(values = c("#228b2250", "#0072B250", "#483d8b50")) +
scale_color_manual(values = c("#228b22", "#0072B2", "#483d8b"), guide = "none") +
stat_density_ridges(quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=1)+
geom_rect(data = data.frame(x = 1),
xmin = -1, xmax = 1, ymin = -Inf, ymax = Inf,
alpha = 0.5, fill = "grey")
The geom_rect()
function does not seem to work with geom_density_ridges()
only geom_density_ridges2()
.
Is this what you are looking for? This is a slight modification of your code. I think we can specifically specify the data frame and aes
for each layer if some elements cannot be recognized.
library(ggplot2)
library(ggridges)
ggplot() +
geom_rect(data = data.frame(x = 1),
xmin = -1, xmax = 1, ymin = -Inf, ymax = Inf,
alpha = 0.5, fill = "gray") +
geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
size=1)+
scale_fill_manual(values = c("#228b2250", "#0072B250", "#483d8b50")) +
scale_color_manual(values = c("#228b22", "#0072B2", "#483d8b"), guide = "none") +
stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=1)