简体   繁体   English

添加ggplot2图例

[英]Adding ggplot2 legend

I've been trying to find an answer to my problem but I couldn't solve it with what I found in the forum. 我一直在尝试找到问题的答案,但是我在论坛中发现的问题无法解决。 I know the key it's do the mapping right (or at least that is what I understood from previous msgs). 我知道关键是正确的映射(或者至少这是我从以前的msg中了解的)。

Here is my code: 这是我的代码:

  dat <- data.frame(
  Individuals = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  Year = c(0, 5, 0, 0, 0, 0, 8, 0, 0, 3),
  end = c(15, 10, 15, 6, 10, 8, 15, 6, 9, 5))

  Person_time_R <- ggplot(dat) + 
  geom_segment(aes(x=Year, y=Individuals, xend=end, yend=Individuals), 
               color=c("blue","red","red","blue","red","red","blue","red","red","red"), 
  size=2) +
  scale_y_reverse() + 
  ggtitle("Person-time") +
  xlab("Years") + 
  ylab("Individuals") +
  theme(
    plot.title = element_text(hjust = 0.5, size=26, face="bold"),
    axis.title.x = element_text(size=20),
    axis.title.y = element_text(size=20)
    ) +
  scale_y_discrete(limits=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) +
  scale_x_continuous(limits = c(0,16)) +
  scale_x_discrete(limits=c( 0, 1, 3, 5, 7, 9, 11, 13, 15))

I would like to have a legend to separate the "red" and "blue" lines... How could I do that? 我想用一个图例来分隔“红色”和“蓝色”线...我该怎么做?

To show the color as a legend, you can add a column showing the type, then mapped to the aes in geom_segment . 要将颜色显示为图例,可以添加一列显示该类型,然后将其映射到geom_segmentaes Finally, use scale_color_manual to specify name and color. 最后,使用scale_color_manual指定名称和颜色。

dat$Type <- c(1, 2, 2, 1, 2, 2, 1, 2, 2, 2)

ggplot(dat) + 
  geom_segment(aes(x=Year, y=Individuals, xend=end, yend=Individuals, colour = factor(Type)), 
               size = 2) +
  scale_color_manual(values = c("blue", "red"), name = "Type") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM