1

I have been trying to plot a Normal Q-Q plot with a red line across, in R with ggplot2. I have been unable to add a legend (with LaTeX math) to explain the red line

Here is the code for the basic figure:

ggplot(stdres_df, aes(sample=stdres)) + 
  stat_qq(color="black") +
  geom_abline(slope = 1, 
              intercept = 0, color ="red")

Thanks in advance.

msx
  • 555
  • 1
  • 5
  • 11
  • Can you show what you've tried so far? – joran Feb 10 '17 at 22:20
  • This is my last unsuccessful attempt: `code` ggplot(stdres_df, aes(sample=stdres)) + stat_qq(color="black") + geom_abline(aes(linetype = "line"), slope = 1, intercept = 0, color ="red") scale_color_manual("", labels = c("line"="Test")) – msx Feb 10 '17 at 22:30
  • It would help if you provide a minimal dataset. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – lizzie Feb 10 '17 at 23:48

2 Answers2

2

To get a legend, you need to map something to a color aesthetic inside a call to aes(). In this case, there's no grouping variable to map to colour, but you can just map colour to the name you want to use for the red line.

The line will be red by default, because ggplot uses hcl(15, 100, 65) (a light red) as the first color in its default color palette. However, you can set the color to whatever you want using scale_colour_manual, as shown in the example below. For example:

set.seed(2)
df <- data.frame(y = rnorm(200))

ggplot(df, aes(sample = y)) + 
  stat_qq() +
  geom_abline(aes(slope=1, intercept=0, colour="Test"), size=1) +
  coord_equal(xlim=range(df$y)) +
  labs(colour="") +
  scale_colour_manual(values="red")

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285
0

Something like this?

ggplot() + 
stat_qq(aes(sample=1:100), distribution = qt,dparams = list(df=5)) +
geom_abline(aes(linetype = "line"), slope = 1, intercept = 0, color ="red") +
geom_text(aes(3, 0, label = "TEXT HERE"))
lizzie
  • 606
  • 6
  • 15
  • This does not work, "geom_abline(): Ignoring `mapping` because `slope` and/or `intercept` were provided." This is despite it being consistent with how legends can be done for geom_smooth. – Richard DiSalvo Jul 13 '22 at 14:13