我正在努力获得直方图上显示的两个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))
有没有办法强制图例显示(对于vlines),即使直方图没有美学填充?
我已经在stackoverflow上尝试了许多可能的解决方案,但没有成功。
非常感谢任何帮助。
谢谢!
答案 0 :(得分:3)
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"))
此方法可以更好地扩展,并且涉及单个geom_vline
而不是几个。
data.frame
,并使用描述标签和值的列geom_vline
将xintercept
映射到值,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