我有以下简单的折线图,带有表示沿y轴感兴趣的阈值的色带。
library(ggplot2)
main.df <- data.frame(time = c(1:20, 1:20),
level = runif(40),
type = c(rep('A', 20), rep('B', 20)))
gg <- ggplot(main.df, aes(x = time, y = level, colour = type))
gg + geom_ribbon(ymin = 0.1, ymax = 0.25, fill = 'green') +
geom_ribbon(ymin = 0.25, ymax = 0.5, fill = 'yellow') +
geom_ribbon(ymin = 0.5, ymax = 0.95, fill = 'red') +
geom_line()
我已多次尝试设置data
的{{1}}属性,以便为我提供更多灵活性并清理代码。这是一个这样的例子。
geom_ribbon
这个特殊的错误是美学缺失的错误。有趣的是,在前面的例子中没有问题。我已经尝试设置x和y,它似乎是rib.df <- data.frame(low = c(0.1, 0.25, 0.5), high = c(0.25, 0.50, 0.95),
lab = c('green', 'yellow', 'red'))
gg + geom_ribbon(data = rib.df,
aes(ymin = low, ymax = high, fill = lab),
inherit.aes=FALSE) + geom_line()
内部的所有组合而不是。我还不清楚为什么有时aes
想要一个geom_ribbon
而不是必需的美学。
总结我的问题:如何调用y
设置geom_ribbon
参数以获得类似于上述手动调用的结果?
我也很高兴了解使用其他data
获得类似视觉效果的有效方法。
答案 0 :(得分:4)
我会这样做:
rib2 = rbind(rib.df, rib.df)
rib2$x = rep(c(-Inf, Inf), each = nrow(rib.df))
gg + geom_ribbon(data = rib2,
aes(x = x, ymin = low, ymax = high, fill = lab),
inherit.aes=FALSE) +
geom_line()
使色带具有ymin和ymax值,其对于各种x值改变。在这种情况下,您只需绘制矩形,可以使用geom_rect
进行简化,在这种情况下,您可以在xmin = -Inf, xmax = Inf
之外设置aes()
并使用rib.df
从你的问题。这样您就不必将数据加倍,以显示ymin和ymax在min和max x值处是相同的。
gg + geom_rect(data = rib.df,
aes(ymin = low, ymax = high, fill = lab),
xmin = -Inf, xmax = Inf,
inherit.aes=FALSE) +
geom_line()