I have tried to find the answer and test different suggestions on how to deal with my problem. I need the graph to show the legend with the name of the columns (the variable column after I reshape2::melt(df)), and the line style.
I have a feeling it might be really easy, but I am struggling on how to not have the legend repeated.
I would like to know how to have one legend with the line style as the left legend and the color of the line as the right legend. Sorry if it has been answered before.
df <- bind_cols(c(1979:2019),sample(1:200,41),sample(1:200,41),sample(1:200,41),sample(1:200,41))
colnames(df) <- c("Dates","Column1","Column2",
"Column3","Column4")
ggplot(reshape2::melt(df, id.var = "Dates"),
aes(`Dates`,value,colour = variable,group = variable))
# geom_point()
geom_line(aes(linetype=variable, colour = variable))
scale_linetype_manual(values=c("solid","dotted", "twodash", "dashed"))
theme_classic()
labs(x = " Period", y = "Number of X detected", color='', show.legend = F)
theme(axis.text.x = element_text(angle = 90, vjust = 1.5, hjust=1.5))
scale_color_manual(values = c("steelblue3","red2", "darkgreen","pink"))
theme(legend.position = "bottom",legend.text = element_text(size = 13),
axis.text = element_text(size = 10),
axis.title.x = element_text(size = 13),
axis.title.y = element_text(size = 13),legend.title=element_blank())
CodePudding user response:
If you mean combine into one legend, with colour and linetype varying across the four variables, then making sure the two scale_
s give the same name matches them accordingly:
library(ggplot2)
df <- bind_cols(c(1979:2019),sample(1:200,41),sample(1:200,41),sample(1:200,41),sample(1:200,41))
colnames(df) <- c("Dates","Column1","Column2",
"Column3","Column4")
ggplot(reshape2::melt(df, id.var = "Dates"),
aes(`Dates`,value,colour = variable,group = variable))
geom_line(aes(linetype=variable, colour = variable))
scale_linetype_manual("", values=c("solid","dotted", "twodash", "dashed"))
theme_classic()
labs(x = " Period", y = "Number of X detected")
theme(axis.text.x = element_text(angle = 90, vjust = 1.5, hjust=1.5))
scale_color_manual("", values = c("steelblue3","red2", "darkgreen","pink"))
theme(legend.position = "bottom",legend.text = element_text(size = 13),
axis.text = element_text(size = 10),
axis.title.x = element_text(size = 13),
axis.title.y = element_text(size = 13),legend.title=element_blank())
That's if I understand your question correctly!
Created on 2022-03-16 by the reprex package (v2.0.1)