ggplot2 cross effect on legend

陌路散爱 提交于 2019-12-11 03:02:02

问题


I'm trying to plot two normal distributions and two vlines indicating the means. When I do so with ggplot2, the legend becomes a cross, making it hard to see that one of them is a dashed line.

ggplot(data = data.frame(x = c(-1, 6)), aes(x)) +
  stat_function(fun = dnorm, n = 100, args = list(mean = 2, sd = 1), aes(linetype = "a")) +
  stat_function(fun = dnorm, n = 100, args = list(mean = 3, sd = 1), aes(linetype = "b")) +
  scale_linetype_manual("Density Function", values = c(1, 2)) +
  labs(x = "Value", y = "Probability Density") +
  geom_vline(aes(xintercept = 2, colour = "mean1"), show.legend = TRUE) +
  geom_vline(aes(xintercept = 3, colour = "mean2"), show.legend = TRUE, linetype = 2) +
  scale_colour_manual("Mean", values = c(mean1 = "#F8766D", mean2 = "#C77CFF"), 
                      labels = c("Mean a", "Mean b")) +
  ggtitle("Legend Help")


回答1:


ggplot(data = data.frame(x = c(-1, 6)), aes(x)) +
  stat_function(
    fun = dnorm, n = 100, args = list(mean = 2, sd = 1), aes(linetype = "a")
  ) +
  stat_function(
    fun = dnorm, n = 100, args = list(mean = 3, sd = 1), aes(linetype = "b")
  ) +
  geom_vline(
    data = data.frame(
      xintercept = c(2, 3), colour = c("mean1", "mean2"),
      stringsAsFactors = FALSE
    ),
    aes(xintercept = xintercept, colour = colour)
  ) +
  scale_colour_manual(
    name = "Mean", 
    values = c(mean1 = "#F8766D", mean2 = "#C77CFF"), 
    labels = c("Mean a", "Mean b")
  ) +
  scale_linetype_manual("Density Function", values = c(1, 2)) +
  labs(
    x = "Value", y = "Probability Density", title = "Legend Help"
  ) 

show.legend=TRUE was forcing inheritance across all line aesthetics. Leaving it NA removes the inheritance and the fact that you used mapped aesthetics for the vline (which I modified a bit) means you get the extra vline legend for free anyway.




回答2:


This discussion on GitHub looks like it was addressing a similar issue.

The fix that Hadley recommended was to call show.legend = NA

I reproduced your plot doing this (full code below), and the issue went away:

ggplot(data = data.frame(x = c(-1, 6)), aes(x)) +
stat_function(fun = dnorm, n = 100, args = list(mean = 2, sd = 1), aes(linetype = "a")) +
stat_function(fun = dnorm, n = 100, args = list(mean = 3, sd = 1), aes(linetype = "b")) +
scale_linetype_manual("Density Function", values = c(1, 2)) +
labs(x = "Value", y = "Probability Density") +
geom_vline(aes(xintercept = 2, colour = "mean1"), show.legend = NA) +
geom_vline(aes(xintercept = 3, colour = "mean2"), show.legend = NA, linetype = 2) +
scale_colour_manual("Mean", values = c(mean1 = "#F8766D", mean2 = "#C77CFF"), 
                  labels = c("Mean a", "Mean b")) +
ggtitle("Legend Help")



来源:https://stackoverflow.com/questions/53355198/ggplot2-cross-effect-on-legend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!