简体   繁体   中英

How to add legend to ggplot2 line with point plot?

I have tried many codes, but always fail to add legend for the graph.I want to add legend for measured red point and simulated black line The graph is still missing legend with the code below

    library(foreign)
    library(ggplot2)
    library(dplyr)
    library(readxl)
    library(scales)
    Sys.setlocale("LC_TIME", "English")
    X0_40cm <- read_excel("C:/Users/Connie/Desktop/LAI/Wheat_2017-2018.xlsx")
    View(X0_40cm)
    ggplot(X0_40cm, aes(Date,LAI,group=1))+
      geom_point(data=subset(X0_40cm, Condition=="Measured"),col="red")+
      geom_line(data=subset(X0_40cm, Condition=="Simulated"),col="black")+
      theme(legend.position=c(0.85,0.80))+
      scale_y_continuous(limits = c(0,3)) +
      labs(title="Winter wheat of I plot",y="LAI",x="Date")+
      theme_update(plot.title=element_text(hjust=0.5))

An automatic legend is only drawn if you map a variable on the color aesthetic. In your case map Condition on color and set colors manually. Try this:

    ggplot(mapping = aes(Date, LAI, color = Condition, linetype = Condition, shape = Condition))+
  geom_point(data=subset(X0_40cm, Condition=="Measured"))+
  geom_line(data=subset(X0_40cm, Condition=="Simulated"))+
  scale_color_manual(values = c("red", "black")) +
  scale_linetype_manual(values=c(NA,1)) +
  scale_shape_manual(values=c(16,NA)) +
  theme(legend.position=c(0.85,0.80))+
  scale_y_continuous(limits = c(0,3)) +
  labs(title="Winter wheat of I plot",y="LAI",x="Date")
  theme_update(plot.title=element_text(hjust=0.5))

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