vline传奇没有在geom_histogram类型的情节中显示

时间:2015-12-09 18:15:20

标签: r ggplot2

我正在努力获得直方图上显示的两个vline元素的图例。我在vline元素上设置show_guide = T以强制显示图例,但它没有帮助。

我怀疑这是因为geom_histogram图只显示了一系列数据。但不确定如何强制图例显示在第一位。

ggplot(mttr, aes(x=Resolution.Time)) +
  geom_histogram(binwidth=0.5) +
  geom_vline(aes(xintercept=mean(Resolution.Time, na.rm=T)),
             color="red", linetype="dashed", size=1, show_guide=T) +
  geom_vline(aes(xintercept=median(Resolution.Time, na.rm=T)),
             color="green", linetype="dashed", size=1, show_guide=T) + 
  xlim(c(0,40)) +
  xlab("Resolution Time (days)") # + theme(legend.position=c(1,0), legend.justification=c(1,0))

histogram with mean and median vlines

有没有办法强制图例显示(对于vlines),即使直方图没有美学填充?

我已经在stackoverflow上尝试了许多可能的解决方案,但没有成功。

非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:3)

方法1:手动映射颜色

  • colour=<your label>放入aes
  • geom_vline函数中
  • 添加scale_color_manual并将标签正确映射到您想要的颜色

示例:

mttr <- data.frame(Resolution.Time = rexp(1000, 0.25))

ggplot(mttr, aes(x=Resolution.Time)) +
  geom_histogram(binwidth=0.5) +

  # Notice that I have color = "Mean" inside aes
  geom_vline(aes(xintercept=mean(Resolution.Time, na.rm=T), color = "Mean"),
             linetype="dashed", size=1, show_guide=T) +

  # Here I have have color = "Median" inside aes
  geom_vline(aes(xintercept=median(Resolution.Time, na.rm=T), color = "Median"),
             linetype="dashed", size=1, show_guide=T) + 

  xlim(c(0,40)) +
  xlab("Resolution Time (days)") +

  # Here I map my labels, "Mean" and "Median", to their colors
  # The legend title is "Statistics"
  scale_color_manual("Statistics", values = c("Mean" = "red", "Median" = "green"))

enter image description here

方法2:创建单独的数据框以绘制垂直线

此方法可以更好地扩展,并且涉及单个geom_vline而不是几个。

  • 为要绘制的垂直线创建data.frame,并使用描述标签和值的列
  • 只有一个geom_vlinexintercept映射到值,color映射到标签
  • (可选)通过选择适当的scale_color_*()
  • 来控制颜色

示例:

# Create a data frame with two columns, a label and a value
vlines = data.frame("Statistic" = c("Mean", "Median"),
                    "Value" = c(mean(mttr$Resolution.Time), median(mttr$Resolution.Time)),
                    stringsAsFactors = FALSE)

# Plot
ggplot(mttr, aes(x=Resolution.Time)) +
  geom_histogram(binwidth=0.5) +

  # Here we have a single geom_vline call
  # Map the xintercept to Value, color to Statistic
  # Specify data = vlines outside the aes function
  geom_vline(aes(xintercept = Value, color = Statistic),
             linetype = "dashed", size = 1, show_guide = TRUE, data = vlines) +

  xlim(c(0,40)) +
  xlab("Resolution Time (days)") # + scale_color_*() to change your colors

enter image description here