我想在棱线图中添加垂直线段,其直方图显示定制的分位数。
如果我用..x..
映射填充颜色,我设法获得了垂直线段,但是我想在密度图中显示分位数。我写了以下代码:
library(datasets)
library(ggplot2)
data("iris")
iris_lines <- data.frame(Species = c("setosa", "versicolor", "virginica"),
x0 = c(5, 5.9, 6.5))
Figure1 <- ggplot(iris, aes(x=Sepal.Length, y=Species, fill=(..quantile..))) +
geom_density_ridges_gradient(jittered_points = FALSE, calc_ecdf = TRUE, quantile_lines = c(TRUE), quantiles =c(0.1,0.25,0.75,0.9),scale=0.9, color='white')+
geom_segment(data = iris_lines, aes(x = x0, xend = x0, y = as.numeric(Species), yend = as.numeric(Species) + c(.9,.5,.5)), color = "red") + scale_y_discrete(expand = c(0.01, 0))
Figure1
如果我将填充色映射为fill = ..x..
,则该代码将起作用,我得到三条垂直线,分别代表每个密度图的平均值;但是,如果将填充颜色映射为fill = ..quantile..
,则会出现以下错误:
Error in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 1, 3
答案 0 :(得分:0)
漂亮的图表!
将inherit.aes = F
添加到第二个几何中,这样它就不会尝试将您的数据与ggplot(aes()
调用中的填充计算进行匹配。
Figure1 <- ggplot(iris, aes(x=Sepal.Length, y=Species, fill=(..quantile..))) +
geom_density_ridges_gradient(jittered_points = FALSE,
calc_ecdf = TRUE,
quantile_lines = c(TRUE),
quantiles =c(0.1,0.25,0.75,0.9),
scale=0.9, color='white') +
geom_segment(data = iris_lines,
aes(x = x0, xend = x0,
y = as.numeric(Species), yend = as.numeric(Species) + c(.9,.5,.5)),
color = "red", inherit.aes = F) + #### HERE ####
scale_y_discrete(expand = c(0.01, 0))
Figure1
编辑:
OP在评论中询问有选择地标记一些元素并为中线添加标签。这是一种方法,可能不是最胖的。
Figure1 <- ggplot(iris, aes(x=Sepal.Length, y=Species,
fill = (..quantile..),
color = (..quantile..))) +
geom_density_ridges_gradient(jittered_points = FALSE,
calc_ecdf = TRUE,
quantile_lines = c(TRUE),
quantiles =c(0.1,0.25,0.75,0.9),
scale=0.9, color='white') +
geom_segment(data = iris_lines,
aes(x = x0, xend = x0, fill = "median",
y = as.numeric(Species),
yend = as.numeric(Species) + c(.9,.5,.5),
color = "median")) + #### HERE ####
scale_y_discrete(expand = c(0.01, 0)) +
scale_color_manual(name = "quantile",
limits = c(1:3, "median"),
values = alpha("firebrick1", c(0, 0, 0, 1)),
labels = c("<10%", "10-25%", "IQR", "median")) +
scale_fill_manual(name = "quantile",
limits = c(1:3, "median"),
values = c("cadetblue", "coral", "orange", "white"),
na.value = "gray30",
labels = c("<10%", "10-25%", "IQR", "median"))
Figure1