简体   繁体   中英

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).

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 . Finally, use scale_color_manual to specify name and color.

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") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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