Kate
Kate

Reputation: 45

Create a legend for qplot graph with stat_summary

I have a file which contains a data frame. Here is the link to the file

tmp <- read.csv("tmp.csv")
m <- qplot(UW_rank, number_correction, data = tmp, 
       alpha = I(1/3), 
       geom = c("point"),
       xlab = "Underwriter rank",
       ylab = "Number of SEC letters",
       main = "Number of SEC Letters and UW Rank",
      ) 
m <- m + stat_summary(aes(colour = "mean"), fun.y = mean, 
                  geom = "line",
                  color = "red",
                  size = 1.1)

As a result I have the following picture enter image description here

I was to add a legend to this graph which will explain that red line is the mean. How can I do that. I have tried scale_fill_manual and geom_text but was not able to figure out how to make it work.

Upvotes: 1

Views: 1111

Answers (1)

eipi10
eipi10

Reputation: 93761

@joran's approach of pre-summarizing the data will work fine (and if you have a large data set, it will be faster than stat_summary), but you can also do it directly by mapping a color aesthetic to "mean" in stat_summary and then adding some additional code to get the colors and labels you want. I've used the built-in mtcars data set as an example:

p1 = ggplot(mtcars, aes(cyl,mpg)) + 
        geom_point() 

p1 +
  stat_summary(fun.y=mean, geom="line", aes(cyl, mpg, colour="mean")) +
  scale_colour_manual(values=c("mean"="blue")) +  # Set line color to blue
  labs(colour="")  # Get rid of the redundant legend title

enter image description here

Upvotes: 3

Related Questions