在ggplot中添加图例

时间:2019-08-27 11:08:02

标签: r ggplot2 legend

我知道这个问题与之前提出的问题类似,但是建议的解决方案似乎并不适用。

我将问题设置如下

mat1 <- NULL
mat2 <- NULL
mat1 <- data.frame(matrix(nrow =16, ncol =2, data = rnorm(32, 0, 1)))
mat2 <- data.frame(matrix(nrow =16, ncol =2, data = rnorm(32, 0, 1)))
mat1[,1] = mat2[,1] = 1:16
colnames(mat1) = c("Window", "CM")
colnames(mat2) = c("Window", "FM")

ggplot() +
  geom_line(data = mat1, aes(x = mat1$Window, y= mat1$CM), linetype ="twodash", color ="steelblue") + 
  geom_line(data = mat2, aes(x = mat2$Window, y= mat2$FM), color = "black") +
  theme_classic() + xlab("Quater after alpha assessment") + ylab("Estimated Coefficient") + labs(fill = "cohort model")

我想添加一个图例。具体来说,我希望将蓝线标记为CM,将黑线标记为FM

2 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用annote()

ggplot() +
  geom_line(data = mat1, aes(x = mat1$Window, y= mat1$CM), linetype ="twodash", color ="steelblue") + 
  geom_line(data = mat2, aes(x = mat2$Window, y= mat2$FM), color = "black") +
  theme_classic() + xlab("Quater after alpha assessment") + ylab("Estimated Coefficient") + labs(fill = "cohort model") +
  xlim(NA,18) + 
  annotate(geom="text", x=16.5, y=1.51232841, label="CM", color="blue", size=3) +
  annotate(geom="text", x=16.5, y=-0.487350382, label="FM", color="black", size=3)

您可以使用x=y=轻松地更改和调整位置。我还略微扩展了x缩放的上限,以使文本适合。

当然,我不知道这是否足以满足您的需求。否则,您也可以将文本字段添加为图例。但这将是最简单,最快的方法。

enter image description here

答案 1 :(得分:1)

在这种情况下,我认为将数据转换为ggplot的适当格式通常是最容易的。然后,您可以正确使用所有ggplot工具集。

library(tidyverse)

mat3 = bind_cols(mat1, mat2) %>%
  select(-Window1) %>%
  gather(type, value, -Window)

mat3 %>%
  ggplot(aes(x = Window, y = value, group = type, color = type, linetype = type)) +
  geom_line() +
  scale_color_manual("cohort model",
                     values = c("CM" = "steelblue","FM" = "black"),
                     breaks = c("CM", "FM")) +
  scale_linetype_manual("cohort model",
                        values = c("twodash", "solid"),
                        breaks = c("CM", "FM")) +
  labs(x = "Quater after alpha assessment", y = "Estimated Coefficient") +
  theme_classic()

enter image description here

相关问题