Hi I would like to add a legend to my chart in R. I am using the gf_line function. The data for plotting have the following structure:
my_data_frame1.csv:
"date","weekday","percentage","mean","bw_1985_stat","bw_1985_signif"
2020-03-24,"Dienstag",100,0.00890943122766354,0.525420167433504,""
2020-03-25,"Mittwoch",100,0.018212241556184,1.07403926954146,""
2020-03-26,"Donnerstag",100,-0.0180547637332521,-1.06475225424524,""
2020-03-27,"Freitag",100,-0.0371849767345406,-2.19292749476635,"**"
2020-03-30,"Montag",100,-0.00239747352191924,-0.141387357634338,""
2020-03-31,"Dienstag",100,0.0643694957679411,3.79609319380439,"***"
my_data_frame2.csv:
"date","weekday","percentage","mean","bw_1985_stat","bw_1985_signif"
2020-03-24,"Dienstag",100,0.0107312075505574,1.03582917607354,""
2020-03-25,"Mittwoch",100,-0.00192882819620307,-0.186180027909036,""
2020-03-26,"Donnerstag",100,0.009296705716626,0.897363971135818,""
2020-03-27,"Freitag",100,0.0031217826218022,0.30132988349984,""
2020-03-30,"Montag",100,-0.000401347125233452,-0.038740007598535,""
2020-03-31,"Dienstag",100,0.0215827577500007,2.08327441923503,"**"
simple example:
returns1.bw <- read.csv('my_data_frame1.csv') # load data frame1
returns2.bw <- read.csv('my_data_frame2.csv') # load data frame2
returns1.bw[,1]<-as.Date(returns1.bw[,1])
returns2.bw[,1]<-as.Date(returns2.bw[,1])
gf_line(mean ~ date,data= returns1.bw,color= "red") %>%
gf_line(mean ~ date,data= returns2.bw,color= "green") %>%
gf_hline(yintercept= 0,linetype= 2) %>%
legend(x = "topleft", legend=c("Equation 1", "Equation 2"), fill = c("blue","red"))
Unfortunately, the legend does not appear in my chart. Many thanks Pete
CodePudding user response:
First of all, I would highly recommend you to use ggplot2 which is way easier to use. What you could do is create a column with the value you want to display in your legend and add this column name to your color
argument which will be the legend title like this:
library(ggformula)
returns1.bw[,1]<-as.Date(returns1.bw[,1])
returns2.bw[,1]<-as.Date(returns2.bw[,1])
# Add column with the name for in legend
returns1.bw$legend <- "Equation 1"
returns2.bw$legend <- "Equation 2"
gf_line(mean ~ date, data= returns1.bw,color=~legend) %>%
gf_line(mean ~ date,data= returns2.bw, color=~legend) %>%
gf_hline(yintercept= 0,linetype= 2)
#> Warning: geom_hline(): Ignoring `mapping` because `yintercept` was provided.
Created on 2022-08-20 with reprex v2.0.2