[英]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.