向时序数据ggplot添加图例

时间:2019-09-17 11:40:30

标签: r ggplot2 legend

我之前问过类似的问题,但是以前的代码似乎无法解决我的问题。

特别是我想在下面的图中添加传奇。我希望将暗线命名为“集群1”,将钢蓝线命名为“集群2”,将黑线标记为“集群3”。我在下面提供了我的尝试。我希望代码只需要对其做一点改动。图例不需要标题,但可以根据需要称为“图例”或“键”。

mat1 <- data.frame(matrix(nrow =10, ncol =4))
colnames(mat1) = c("Date", "Cluster 1", "Cluster 2", "Cluster 3")
date.start = as.Date("2000-01-01")
date.end = as.Date("2000-10-01")
date = seq(from = date.start, to = date.end, by = "month")
mat1[,1] = date
mat1[,2:4] = rnorm(30,0,1)
mat1 %>% ggplot(aes(x= Date, group=1)) + 
  geom_line(aes(y = `Cluster 1`), color = "darkred", linetype = "solid", size=1) +
  geom_line(aes(y = `Cluster 2`), color="steelblue", linetype="twodash", size =1) + 
  geom_line(aes(y= `Cluster 3`), color = "black", linetype = "longdash", size = 1) +
  scale_colour_manual("Legend",
                      values = c("Cluster 1" = "darkred", "Cluster 2" ="steelblue", "Cluster 3" = "black"),
                      breaks = c("Cluster 1", "Cluster 2", "Cluster 3")) +
  scale_linetype_manual("Legend",
                        values = c("solid", "twodash", "longdash"),
                        breaks = c("Cluster 1", "Cluster 2", "Cluster 3")) +
  xlab("Date") + ylab("Average Coefficient") + ggtitle("HML Factor") + theme_classic() +
  theme(
    plot.title = element_text(color = "black", size = 12, face = "bold"),
    axis.title = element_text(size = 12)
  )

1 个答案:

答案 0 :(得分:1)

我建议您先调整您的数据结构,以实现您的目标。

您可以使用tidyr的gather函数执行此操作,并在mat1[,2:4] = rnorm(30,0,1)行之后执行此操作:

mat1 <- mat1 %>% 
  tidyr::gather(cluster, value, `Cluster 1`:`Cluster 3`)

然后添加一个geom_line调用以替换您当前拥有的三个:

mat1 %>% ggplot(aes(x= Date, y = value)) + 
  # geom_line(aes(y = `Cluster 1`), color = "darkred", linetype = "solid", size=1) +
  # geom_line(aes(y = `Cluster 2`), color="steelblue", linetype="twodash", size =1) + 
  # geom_line(aes(y= `Cluster 3`), color = "black", linetype = "longdash", size = 1) +
  geom_line(aes(colour = cluster, linetype = cluster), size = 1) +
  scale_colour_manual(values = c("Cluster 1" = "darkred", "Cluster 2" ="steelblue", "Cluster 3" = "black")) +
  scale_linetype_manual(values = c("Cluster 1" = "solid", "Cluster 2" = "twodash", "Cluster 3" = "longdash")) +
  xlab("Date") + ylab("Average Coefficient") + ggtitle("HML Factor") +     theme_classic() +
  theme(
    plot.title = element_text(color = "black", size = 12, face = "bold"),
    axis.title = element_text(size = 12)
  )

编辑:为geom_line美学添加了线型