ggplot2:更改置信区域的颜色以匹配行

时间:2017-08-07 19:00:08

标签: r ggplot2

我希望每行后面的置信区域与该行的颜色相同。

以下是我的一些数据:

df <- structure(list(yrmonth = structure(c(1483228800, 1483228800, 
1483228800, 1485907200, 1485907200, 1485907200, 1488326400, 1488326400, 
1488326400, 1491004800, 1491004800, 1491004800), class = c("POSIXct", 
"POSIXt"), tzone = "UTC"), index = structure(c(1L, 3L, 5L, 1L, 
3L, 5L, 1L, 3L, 5L, 1L, 3L, 5L), .Label = c("N-S", "N-S", "E-W", 
"E-W", "OS"), class = "factor"), N = c(2, 2, 1, 2, 2, 1, 2, 2, 
1, 2, 2, 1), data = c(129, 141, 27, 150.5, 209, 87, 247.5, 243, 
188, 223, 226.5, 170), sd = c(1.4142135623731, 4.24264068711928, 
NA, 4.94974746830583, 65.0538238691624, NA, 12.0208152801713, 
8.48528137423857, NA, 5.65685424949238, 0.707106781186548, NA
), se = c(1, 3, NA, 3.5, 46, NA, 8.5, 6, NA, 4, 0.5, NA), ci = c(12.7062047361747, 
38.1186142085241, NA, 44.4717165766114, 584.485417864036, NA, 
108.002740257485, 76.2372284170481, NA, 50.8248189446988, 6.35310236808735, 
NA)), .Names = c("yrmonth", "index", "N", "data", "sd", "se", 
"ci"), row.names = 31:42, class = "data.frame")

我的情节:

ggplot(df, aes(x=yrmonth,y=data, colour=factor(index), group=index)) + 
  geom_line(size=.4) + 
  geom_ribbon(aes(ymin=data-sd, ymax=data+sd, linetype = NA), alpha = 0.2) +
  scale_color_manual(values = c("purple2","sienna3","green4"))

enter image description here

E-W信心区域将是西耶娜。 N-S将是紫色的。

1 个答案:

答案 0 :(得分:2)

只需将fill=index添加到aes

即可
ggplot(df, aes(x=yrmonth,y=data, colour=factor(index), group=index)) + 
  geom_line(size=.4) + 
  geom_ribbon(aes(ymin=data-sd, ymax=data+sd, linetype = NA, fill = index), alpha = 0.2) +
  scale_color_manual(values = c("purple2","sienna3","green4")) +
  scale_fill_manual(values = c("purple2","sienna3","green4"))