如何同时控制geom_line的线条颜色和图例

时间:2021-01-26 20:23:59

标签: r ggplot2

我想控制绘图中线条的颜色,但是遇到了一些困难。这些行由 PARAMCD 组成。 NA 中有 PARAMCD。为了控制图例,我使用了scale_color_discrete。但是当我再次尝试控制颜色时,它不会让我这样做。我确定我做错了,可能定义了太多次颜色。我不熟悉如何控制颜色。请原谅我这么乱的代码。

我用来绘图的代码是:

ggplot(data =df)+
       geom_line(aes(x = ADY, y = AVAL, color = PARAMCD, yaxs="d", xaxs="d"))+
       geom_point(aes(x = ADY, y = AVAL))+
       scale_color_discrete(breaks=c("SYSBP", "DIABP", "PULSE"),name = "Vital signs", labels = c("Systolic BP", "Diastolic BP",  "Pulse"))+
       scale_colour_manual(values=c(DIABP="#512d69",SYSBP="#007254",PULSE="#fd9300"))

输出应该是这样的,但我希望颜色是绿色、橙色和紫色。

enter image description here

有人可以给我一些指导吗?谢谢。

可以使用代码构建示例数据:

df<- structure(list(ADY = c(-6, -6, -6, 1, 1, 1, 8, 8, 8, 15, 15, 
15, 22, 22, 22, 29, 29, 29, 43, 43, 43, 57, 57, 57, 64, 87, 87, 
87, 101, 101, 101), AVAL = c(66, 67, 127, 70, 58, 136, 68, 74, 
140, 145, 74, 58, 75, 72, 149, 82, 66, 143, 86, 60, 159, 64, 
87, 136, NA, 73, 58, 135, 141, 74, 74), PARAMCD = structure(c(3L, 
1L, 2L, 1L, 3L, 2L, 3L, 1L, 2L, 2L, 1L, 3L, 1L, 3L, 2L, 1L, 3L, 
2L, 1L, 3L, 2L, 3L, 1L, 2L, NA, 1L, 3L, 2L, 2L, 1L, 3L), .Label = c("DIABP", 
"SYSBP", "PULSE"), class = "factor")), row.names = c(NA, -31L
), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

试试这个:

ggplot(data = subset(df,!is.na(df$PARAMCD)),
       aes(x = ADY, y = AVAL, color = PARAMCD)) +
  geom_line() +
  geom_point() +
  scale_colour_manual(values = c(
    DIABP = "#512d69",
    SYSBP = "#007254",
    PULSE = "#fd9300"
  ),labels = c("Systolic BP", "Diastolic BP",  "Pulse"))

enter image description here