r - 当 geom_line() 和 geom_segment() 一起使用时,看似不正确的引导颜色

标签 r ggplot2

我正在使用 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")

When geom_segment() comes after geom_line()

如果我先添加 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()

When geom_line() comes after geom_segment()

功能还是错误?如果是第一个,有人可以解释发生了什么吗?

最佳答案

功能(左右)。绘制的引用线是线型的引用线。但是,它必须用某种颜色绘制才能被看到。当美学映射未指定颜色时,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")))

enter image description here

关于r - 当 geom_line() 和 geom_segment() 一起使用时,看似不正确的引导颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478346/

相关文章:

r - 在 ggplot 中将 x 轴标签指向内

r - 使用对数刻度时如何添加垂直线?

r - 如何在 R Markdown 中添加目录?

r - 3D阵列->应用-> 3D阵列

r - 如何用前n个级别(按某种度量标准)加上[other]来替换因子级别?

r - ggmap map 样式存储库?现在 CloudMade 不再提供 API

r - 使用 purrr::map 将多个参数应用于函数

r - geom_smooth 和 geom_label_repel 创建不需要的多个标签

r - 嵌套函数的优缺点

r - 深度测量中的插值步骤