简体   繁体   中英

ggplot2 legend, geom_abline and stat_gg

I have been trying to plot a Normal QQ 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.

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")

在此处输入图片说明

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM