[英]Confidence intervals ggplot2 with different colours based on preselection
我是stackoverflow的新手,如果我的解释不准确,请原谅。 我已经从数据集中绘制了一些置信区间,其中 y = 离散升序数字 (1:31) 到 position 的区间到 y 轴,x = 平均值,下限和上限 95% HPD 区间。 我附上部分数据集:
是的 | X | 降低 | 上 |
---|---|---|---|
1 | 143,580 | 80,675 | 203,670 |
2 | 127,740 | 90,799 | 168,240 |
3 | 134,840 | 98,665 | 174,030 |
4 | 138,660 | 99,682 | 176,360 |
ggplot(data, aes(x, y)) +
geom_point() +
geom_errorbar(aes(xmin = upper, xmax = lower)) +
scale_y_continuous(position = "right") +
scale_x_reverse() +
ggtitle("Molecular Dating (95% HPD intervals)") +
theme(plot.title = element_text(hjust = 0.5)) +
xlab("Time (years)") +
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
)
我想在置信区间上应用 2 种不同的颜色,例如第 8、第 17 和第 31 种颜色为红色,第 4、第 6 和第 9 种颜色为灰色。 我尝试了各种各样的东西,但我认为我错过了一些东西。 有人可以建议一种可行的方法吗?
非常感谢您,感谢您的反馈!
您可以创建一个二分变量和color
它来审美。
在下面的代码中,我使用sample
随机选择值。 这应该由您的 colors 分配标准替换。 然后,在 scale_color_manual 中设置实际的scale_color_manual
。
此外,您的数据以逗号作为小数点,这就是我使用dec = ","
读取它的原因
x <- 'y x lower upper
1 143,580 80,675 203,670
2 127,740 90,799 168,240
3 134,840 98,665 174,030
4 138,660 99,682 176,360'
data <- read.table(textConnection(x), header = TRUE, dec = ",")
suppressPackageStartupMessages({
library(ggplot2)
library(dplyr)
})
set.seed(2022)
colors <- sample(c("this", "that"), nrow(data), replace = TRUE)
data$colors <- colors
ggplot(data, aes(x, y, color = colors)) +
geom_point() +
geom_errorbar(aes(xmin = upper, xmax = lower)) +
scale_color_manual(values = c(this = "grey", that = "red")) +
scale_y_continuous(position = "right") +
scale_x_reverse() +
xlab("Time (years)") +
ggtitle("Molecular Dating (95% HPD intervals)") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
由代表 package (v2.0.1) 于 2022 年 8 月 6 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.