将图例添加到geom_vline

Pre*_*deo 16 r ggplot2

我知道之前已经问过这个问题,但解决方案对我来说似乎并不适用.

我想要做的是用不同颜色的直方图表示我的中位数,平均值,上下分位数,然后在图中添加一个图例.这是我到目前为止,我试图使用scale_color_manualscale_color_identity给我一个传奇.似乎没有什么工作.

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)
Run Code Online (Sandbox Code Playgroud)

结果情节

Rol*_*and 21

你需要在里面映射颜色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"))
Run Code Online (Sandbox Code Playgroud)

结果情节

  • 即使我将“show_guide”更改为“show.legend”(当 R 抱怨时)并将其添加到我的每个“geom_vlines”中,也对我不起作用。 (2认同)
  • 您可能已将颜色写在 aes() 之外。不需要“show_guide”或“show.legend”。您的“color=”需要位于“aes()”中。 (2认同)