r - 如何将 geom_segment 添加到 geom_density_ridges_gradient?
问题描述
我想将垂直线段添加到直方图显示自定义分位数的山脊线图中。
如果我用..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
解决方案
不错的图表!
添加inherit.aes = F
到第二个 geom,这样它就不会尝试将您的数据与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
推荐阅读
- python - Pylint 类型混淆
- mongodb - MongoDB 副本集升级仲裁器失败。3.6 - 4.0 - 4.2
- java - Java - StringBuilder 的输出
- python - 命令提示符不执行 Python 文件
- python - 从 Cloud Function 到本地 SQL Server,如何使用 pymssql 建立安全连接 (SSL/TLS)
- azure - 在范围函数后删除字符 - Helm
- c++ - 如何将变量元素转换为 std::string ( c++ )
- r - 闪亮的仪表板:将对象添加到输入列表而不单击侧边栏选项卡
- c# - 使用 c# 执行原始 Mongodb 命令/查询
- javascript - 在 google docs 中绘制某些字词 - Google Apps Script