0

I am trying to add a legend to the following code in R, gplot2 for a stacked area chart:

plot1<-ggplot(data=agegenderdata,
              aes(x=agegenderdata$Year,
                  y=agegenderdata$`Obesity Inpatients`,
                  fill=agegenderdata$`Age Category`))
plot1withGeom <- plot1 + geom_area(aes(colour=agegenderdata$`Age Category`, fill=agegenderdata$`Age Category`)) 

plot1withGeom + labs(x = "Year", y = "Obesity Inpatients", title = "graph" ) 

However, when checking online and trying different methods to change the legend title I have had little luck. Could someone please help.

Greatly appreciated.

Saif
  • 39
  • 1
  • 2
  • 5
  • 1
    You forgot `=` between `title` and `"graph"` in your `labs()`. – hpesoj626 Mar 20 '18 at 13:12
  • `+ggtitle('graph')` – hpesoj626 Mar 20 '18 at 13:13
  • 1
    It is not necessary to specify the name of the data frame in all of your aesthetics. The first command (`data = agegenderdata`) will do – tifu Mar 20 '18 at 13:15
  • Hi, @hpesoj626, thanks for clearing that up. Do you know how i can change the legend title on my graph. – Saif Mar 20 '18 at 13:21
  • @Saif, this is most probably answered elsewhere. Add `+ggtitle("title")`. Also, please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – hpesoj626 Mar 20 '18 at 13:23
  • Also, [this one](https://stackoverflow.com/questions/23635662/editing-legend-text-labels-in-ggplot) – 4rj4n Mar 20 '18 at 15:04

1 Answers1

0

To change the title of a legend, use labs and the aesthetic that the legend corresponds to.

For example:

labs(fill = 'Title for fill legend') 
Mhairi McNeill
  • 1,951
  • 11
  • 20