Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

r - Add legend to geom_vline

I know that this question has been asked before but the solutions don't seem to work for me.

What I want to do is represent my median, mean, upper and lower quantiles on a histogram in different colours and then add a legend to the plot. This is what I have so far and I have tried to use scale_color_manual and scale_color_identity to give me a legend. Nothing seems to be working.

quantile_1 <- quantile(sf$Unit.Sales, prob = 0.25)
quantile_2 <- quantile(sf$Unit.Sales, prob = 0.75)

ggplot(aes(x = Unit.Sales), data = sf) + 
  geom_histogram(color = 'black', fill = NA) + 
  geom_vline(aes(xintercept=median(Unit.Sales)),
            color="blue", linetype="dashed", size=1) + 
  geom_vline(aes(xintercept=mean(Unit.Sales)),
            color="red", linetype="dashed", size=1) +
  geom_vline(aes(xintercept=quantile_1), color="yellow", linetype="dashed", size=1)

resulting plot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to map the color inside the aes:

ggplot(aes(x = Sepal.Length), data = iris) + 
  geom_histogram(color = 'black', fill = NA) + 
  geom_vline(aes(xintercept=median(iris$Sepal.Length),
                 color="median"), linetype="dashed",
             size=1) +
  geom_vline(aes(xintercept=mean(iris$Sepal.Length),
                 color="mean"), linetype="dashed",
             size=1) +
  scale_color_manual(name = "statistics", values = c(median = "blue", mean = "red"))

resulting plot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...