rhys
rhys

Reputation: 1

How to add a legend in R

I know this has been asked a lot but I've tried so many ways and I still can't find a way to reliably add a legend to my R plots.

This is my 'theme'

CustomTheme <- theme(legend.text = element_text(face = "bold", colour = "black", family = "Garamond"),
                     axis.title = element_text(colour = "black", family = "Garamond",face="plain"),
                     axis.line = element_line(size = 0.5, colour = "black"),
                     axis.ticks = element_line(colour = "grey"),
                     panel.grid.major = element_line(colour = "grey"),
                     panel.grid.minor = element_blank(),
                     panel.background = element_rect(fill = "white"),
                     legend.title = element_text(colour = "black", face = "bold", family = "Garamond"),
                     legend.position = c(0.035,0.5),
                     plot.title = element_text(colour = "black", face= "bold", family = "Garamond", size = 14, hjust = 0.5))

and this is my code

CO2_H2O_ratio_all<-ggplot()+
  geom_point(data=CF_Gas_BG,aes(x=DATE,y=H2O/CO2),na.rm=TRUE,size=2,shape=17,colour="#662506")+
  geom_point(data=CF_Gas_BN,aes(x=DATE,y=H2O/CO2),na.rm=TRUE,size=2,shape=19,colour="#ec7014")+
  geom_point(data=CF_Gas_Pisc,aes(x=DATE,y=H2O/CO2),na.rm=TRUE,size=2,shape=15,colour="#fec44f")+
  labs(x = "Date", y = "H2O/CO2 ratio",colour="legend") +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y", limits = as.Date(c("1983-01-01", "2018-01-01"))) +
  ggtitle("H2O/CO2 ratio: Bocca Grande, Bocca Nuova & Pisciarelli (1982-2016")+
  CustomTheme

print(CO2_H2O_ratio_all)

Can anyone offer any help?

Upvotes: 0

Views: 41

Answers (1)

DaveArmstrong
DaveArmstrong

Reputation: 21757

You need to put the aspects that you want to show up in the legend in the aes(). Without your data I can't troubleshoot, but here's what it should look like:

CO2_H2O_ratio_all<-ggplot()+
  geom_point(data=CF_Gas_BG,aes(x=DATE,y=H2O/CO2, shape="BG", colour="BG"),na.rm=TRUE,size=2)+
  geom_point(data=CF_Gas_BN,aes(x=DATE,y=H2O/CO2, shape="BN", colour="BN"),na.rm=TRUE,size=2)+
  geom_point(data=CF_Gas_Pisc,aes(x=DATE,y=H2O/CO2, shape="Pisc", colour="Pisc"),na.rm=TRUE,size=2)+
  scale_shape_manual(values=c(17,19,15)) +
  scale_colour_manual(values=c("#662506", "#ec7014", "#fec44f")) + 
  labs(x = "Date", y = "H2O/CO2 ratio",colour="legend", shape="legend") +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y", limits = as.Date(c("1983-01-01", "2018-01-01"))) +
  ggtitle("H2O/CO2 ratio: Bocca Grande, Bocca Nuova & Pisciarelli (1982-2016")+
  CustomTheme

Upvotes: 1

Related Questions