简体   繁体   中英

Tried to add legend into line plot using ggplot2 but nothing showed up

I tried to add the legend to line plot by using ggplot2 but the result did not show any legend at all.

p = ggplot() + 
  geom_line(data=data1, aes(x = dpi, y = Temp.chick1), color = "blue",size = 1) +
  geom_line(data=data2, aes(x = dpi, y = Temp.chick2),color = "red",size = 1) + 
  geom_line(data=data3, aes(x = dpi, y = Temp.chick3),color = "green",size = 1) +
  geom_line(data=dataC, aes(x = dpi, y = Temp.chickC),color = "black",size = 1) + 
  scale_x_continuous(breaks = seq(from = 1, to = 14, by = 1)) +
  scale_y_continuous(breaks = seq(from = 40, to = 44, by = 0.1)) +
  labs(x = "Day Post Infection",
         y = "Temperature") +
 scale_colour_manual(values=c("blue","red","green","black"))
print(p)

ggplot2 的结果

The issue is that you passed the colors as arguments. You have to map them on the color aes, ie put them inside aes() to get a legend. Also. To get the correct color mapping use a named vector inside scale_color_manual . Try this:

library(ggplot2)

set.seed(42)
data1 <- data.frame(dpi = runif(20), Temp.chick1 = runif(20))
data2 <- data.frame(dpi = runif(20), Temp.chick2 = runif(20))
data3 <- data.frame(dpi = runif(20), Temp.chick3 = runif(20))
dataC <- data.frame(dpi = runif(20), Temp.chickC = runif(20))

p = ggplot() + 
  geom_line(data=data1, aes(x = dpi, y = Temp.chick1, color = "Chicken 1"),size = 1) +
  geom_line(data=data2, aes(x = dpi, y = Temp.chick2,color = "red"),size = 1) + 
  geom_line(data=data3, aes(x = dpi, y = Temp.chick3,color = "green"),size = 1) +
  geom_line(data=dataC, aes(x = dpi, y = Temp.chickC,color = "Chicken Control"),size = 1) + 
  scale_x_continuous(breaks = seq(from = 1, to = 14, by = 1)) +
  scale_y_continuous(breaks = seq(from = 40, to = 44, by = 0.1)) +
  labs(x = "Day Post Infection",
       y = "Temperature") +
  scale_colour_manual(values=c("Chicken 1" = "blue",red = "red",green = "green","Chicken Control" = "black"))
print(p)

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