问题
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 lineThe 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))
回答1:
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))
来源:https://stackoverflow.com/questions/60556330/how-to-add-legend-to-ggplot2-line-with-point-plot