我正在使用 geom_line() 的图上绘制一些线段。令人惊讶的是,geom_line() 的引导(图例)颜色被绘制为我添加到绘图中的最后一个元素的颜色 - 即使它不是 geom_line()。对我来说,这看起来像是一个错误,但由于某种我不明白的原因,这可能是预期的行为。
#Set up the data
require(ggplot2)
x <- rep(1:10, 2)
y <- c(1:10, 1:10+5)
fac <- gl(2, 10)
df <- data.frame(x=x, y=y, fac=fac)
#Draw the plot with geom_segment second, and the guide is the color of the segment
ggplot(df, aes(x=x, y=y, linetype=fac)) +
geom_line() +
geom_segment(aes(x=2, y=7, xend=7, yend=7), colour="red")
如果我先添加 geom_segment,指南上的颜色将如我所料为黑色:
ggplot(df, aes(x=x, y=y, linetype=fac)) +
geom_segment(aes(x=2, y=7, xend=7, yend=7), colour="red") +
geom_line()
功能还是错误?如果是第一个,有人可以解释发生了什么吗?
最佳答案
功能(左右)。绘制的引用线是线型的引用线。但是,它必须用某种颜色绘制才能被看到。当美学映射未指定颜色时,ggplot2 会使用与绘图一致的颜色来绘制它。我推测默认值是最后使用的颜色。这就是为什么当您以不同的顺序绘制它们时您会看到差异。
但是,您可以控制图例的这些细节。
ggplot(df, aes(x=x, y=y, linetype=fac)) +
geom_line() +
geom_segment(aes(x=2, y=7, xend=7, yend=7), colour="red") +
scale_linetype_discrete(guide=guide_legend(override.aes=aes(colour="blue")))
关于r - 当 geom_line() 和 geom_segment() 一起使用时,看似不正确的引导颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478346/