根据R中的值更改颜色的绘图线

时间:2020-05-14 20:31:32

标签: r ggplot2

这是我的桌子:

date        CumRet1     CumRet2     Boom
1973-01-31  1.112309    1.011383    True
1973-02-28  1.120466    1.021701    True
1973-03-31  1.125156    1.030822    True
1973-04-30  1.135342    1.067682    True
1973-05-31  1.136887    1.069136    False
1973-06-30  1.139889    1.071959    False

我想绘制一条线,如果Boom为True,则将累积Return1设为黑色,将蓝色Return2设为蓝色,如果Boom为false,则设为红色。不幸的是,我的代码在图形中产生了三行,第二条累积收益被分组为True或False。谁能帮我解决这个问题?

这是我的方法:

ggplot() +
  geom_line(data = df, aes(x = date, y = CumRet2, color = BOOM), size=1) +
  geom_line(data = df, aes(x = date, y = CumRet1), size=1)

1 个答案:

答案 0 :(得分:1)

这是我理解您问题的最佳猜测。

数据


library(ggplot2)
library(tidyr)

df <- structure(list(date = c("1973-01-31", "1973-02-28", "1973-03-31", 
                              "1973-04-30", "1973-05-31", "1973-06-30"),
                     CumRet1 = c(1.112309, 1.120466, 1.125156, 1.135342, 1.136887, 1.139889), 
                     CumRet2 = c(1.011383, 1.021701, 1.030822, 1.067682, 1.069136, 1.071959),
                     Boom = c("True", "True", "True", "True", "False", "False")), 
                class = "data.frame", row.names = c(NA, -6L))

纠缠

以“长”格式获取数据并为三种情况创建分组,这三种情况将被映射为不同的颜色。

  df <- 
    df %>%
    pivot_longer(cols = starts_with("Cum"), names_to = "var", values_to = "val") %>% 
    mutate(g = case_when(var =="CumRet1" & Boom == "True" ~ "g1",
                         var =="CumRet2" & Boom == "True" ~ "g2",
                         TRUE ~ "g3"))
    

情节

ggplot(df, aes(date, y = val)) +
  geom_line(aes(colour = g, group = var), size = 1)+
  scale_colour_manual(breaks = c("g1", "g2", "g3"), 
                      values = c("black", "blue", "red"),
                      labels = c("Cumulative return 1, Boom; True", 
                                 "Cumulative return 2, Boom; True",
                                 "Cumulative return 1 or 2, Boom; False"))+
  labs(colour = "Cumulative return")+
  theme(legend.position = "bottom")+
  guides(colour=guide_legend(ncol = 2, byrow=TRUE))

enter image description here

reprex package(v0.3.0)于2020-05-14创建