Add legend to ggplot2 line plot
I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:
##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))
All that's left is a simple ggplot command:
ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
scale_colour_manual(values=c("red","green","blue"))
Example plot
Add legend to geom_line() graph in r
ggplot
needs aes
to make a legend, moving colour
inside aes(...)
will build a legend automatically. then we can adjust the labels-colors pairing via scale_color_manual
:
ggplot()+
geom_line(data=Summary,aes(y=Y1,x= X,colour="Y1"),size=1 )+
geom_line(data=Summary,aes(y=Y2,x= X,colour="Y2"),size=1) +
scale_color_manual(name = "Y series", values = c("Y1" = "darkblue", "Y2" = "red"))
How to add a legend manually for line chart
The neatest way to do it I think is to add colour = "[label]"
into the aes()
section of geom_line()
then put the manual assigning of a colour into scale_colour_manual()
here's an example from mtcars
(apologies that it uses stat_summary
instead of geom_line
but does the same trick):
library(tidyverse)
mtcars %>%
ggplot(aes(gear, mpg, fill = factor(cyl))) +
stat_summary(geom = "bar", fun = mean, position = "dodge") +
stat_summary(geom = "line",
fun = mean,
size = 3,
aes(colour = "Overall mean", group = 1)) +
scale_fill_discrete("") +
scale_colour_manual("", values = "black")
Created on 2020-12-08 by the reprex package (v0.3.0)
The limitation here is that the colour and fill legends are necessarily separate. Removing labels (blank titles in both scale_
calls) doesn't them split them up by legend title.
In your code you would probably want then:
...
ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) +
geom_col(aes(fill = gender))+
geom_line(data = impact_end_Current_yr_m_plan,
aes(x=month, y= gender_value, group=1, color="Plan"),
size=1.2)+
scale_color_manual(values = "#288D55") +
...
(but I cant test on your data so not sure if it works)
How to add legend to ggplot2 line with point plot?
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))
Create legend for line chart R GGPlot2
It might help if you put your data into "long" form, such as this for your data frame graphDF
(perhaps using pivot_longer
from tidyr
if necessary):
library(tidyr)
graphDF_long <- pivot_longer(data = graphDF,
cols = c(noCVErr, CVErr),
names_to = "model",
values_to = "errRate")
This creates a new data.frame called graphDF_long
that has a single column for the error rate, and a new column that specifies model:
ks kAxis noCVAcc CVAcc model errRate
<int> <dbl> <dbl> <dbl> <chr> <dbl>
1 1 1 1 0.828 noCVErr 0
2 1 1 1 0.828 CVErr 0.172
3 3 0.333 0.935 0.834 noCVErr 0.0655
4 3 0.333 0.935 0.834 CVErr 0.166
5 5 0.2 0.881 0.816 noCVErr 0.119
6 5 0.2 0.881 0.816 CVErr 0.184
....
Then, you can simplify your ggplot
statement, and use an aesthetic with the column model
for color:
library(ggplot2)
ggplot(data = graphDF_long, aes(x = rev(kAxis), y = rev(errRate), color = model)) +
geom_line() +
geom_point() +
scale_color_manual(values = c("blue", "red"),
labels = c("Cross Validation", "No Cross Validation")) +
ylim(min(graphDF_long$errRate), max(graphDF_long$errRate)) +
ggtitle("The KNN Error Rate for Cross Validated and Non-Cross Validated Models") +
labs(y="Error Rate", x = "1/K")
This will generate the legend automatically:
Add legend to ggplot2 line with point plot
I would approach this problem in two steps.
Generally, to get stuff in the guides, ggplot2 wants you to put "aesthetics" like colour inside the aes() function. I typically do this inside the ggplot() rather than individually for each "geom", especially if everything kind of makes sense in a single dataframe.
My first step would be to remake your dataframe slightly. I would use the package tidyr (part of the tidyverse, like ggplot2, which is really nice for reformatting data and worth learning as you go), and do something like this
#key is the new variable that will be your color variable
#value is the numbers that had been in V2 and V3 that will now be your y-values
data_p %>% tidyr::gather (key = "color", value = "yval", V2, V3)
#now, I would rewrite your plot slightly
P<-(newdf %>% ggplot(aes(x=V1,y=yval, colour=color))
#when you put the ggplot inside parentheses,
#you can add each new layer on its own line, starting with the "+"
+ geom_point()
+ geom_line()
+ scale_color_manual(values=c("#56B4E9","#009E73"))
#theme classic is my preferred look in ggplot, usually
+ theme_classic()
)
Related Topics
Adding a New Column Based Upon Values in Another Column Using Dplyr
Remove Quotes from a Character Vector in R
Using Ggplot2, How to Insert a Break in the Axis
Rstudio Does Not Display Any Output in Console After Entering Code
How to Find the Closest Date to a Given Date
Plotting Two Variables as Lines Using Ggplot2 on the Same Graph
Why Does Summarize or Mutate Not Work With Group_By When I Load 'Plyr' After 'Dplyr'
How to Use R'S Ellipsis Feature When Writing Your Own Function
How to Split Data into Training/Testing Sets Using Sample Function
Adding a Column of Means by Group to Original Data
Divide All Columns by the Value from the 2Nd Column - Apply for All Rows
Add X and Y Axis to All Facet_Wrap
Setting Individual Axis Limits With Facet_Wrap and Scales = "Free" in Ggplot2
Column Name Changes in R for Loop for Defined Data Frame
Quickly Reading Very Large Tables as Dataframes
What Are the Differences Between "=" and "≪-" Assignment Operators