r - 是否可以将 geom_ribbon 扩展到 xlimits?

标签 r ggplot2

我有以下代码(作为示例),我想对其进行调整,以使功能区扩展到整个 xrange,如 geom_hline()做。功能区指示哪些值在可接受的范围内。在我的实际应用程序中,有时没有上限或下限,因此 hline 本身不足以确定值是否在范围内。

library(ggplot2)
set.seed(2016-12-19)
dates <- seq(as.Date('2016-01-01'), as.Date('2016-12-31'), by = 1)
values <- rexp(length(dates), 1)
groups <- rpois(length(dates), 5)
temp <- data.frame(
    date = dates,
    value = values,
    group = groups,
    value.min = 0,
    value.max = 2
)
ggplot(temp, aes(date, value)) +
    geom_ribbon(aes(ymin = value.min, ymax = value.max), fill = '#00cc33', alpha = 0.6) +
    geom_hline(aes(yintercept = value.min)) +
    geom_hline(aes(yintercept = value.max)) +
    geom_point() +
    facet_wrap(~group)

我尝试设置 xgeom_ribbondates同样,但只有部分范围被填充。
我也试过这个:

geom_ribbon(aes(ymin = -Inf, ymax = 2, x = dates), data = data.frame(), fill = '#00cc33', alpha = 0.6)

但随后数据似乎被整个情节覆盖,我收到错误 Error in eval(expr, envir, enclos) : object 'value' not found .即使它可以工作,随着 xlimits 的扩展,范围实际上仍然太窄。

最佳答案

这是一种方法:

ggplot(temp, aes(as.numeric(date), value)) +
  geom_rect(aes(xmin=-Inf, xmax=Inf, ymin = value.min, ymax = value.max), temp[!duplicated(temp$group),], fill = '#00cc33', alpha = 0.6) + 
  geom_hline(aes(yintercept = value.min)) +
  geom_hline(aes(yintercept = value.max)) +
  geom_point() +
  scale_x_continuous(labels = function(x) format(as.Date(x, origin = "1970-01-01"), "%b %y")) + 
  facet_wrap(~group)

enter image description here

请注意,我使用了 as.numeric(date) , 因为否则 Inf-Inf屈服

Error: Invalid input: date_trans works with objects of class Date only



为了获取数值的日期标签,我调整了 scale_x_continuous相应地贴上标签。 (尽管它们在这里并不准确。您可能希望通过使用确切的日期而不是月/年来调整它,或者使用 breaks 参数和例如 seq.Date 设置手动中断。)

另请注意,我使用了 temp[!duplicated(temp$group),]以避免过度绘制,从而保持所需的 alpha 透明度。

关于r - 是否可以将 geom_ribbon 扩展到 xlimits?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220434/

相关文章:

正则表达式在存在多个时提取第一个 date_time 戳

r - 面积图 : cannot get stacking in correct order - legend out of sync with Data

r - 忽略 ggplot2 boxplot + faceting + "free"选项中的异常值

r - 多重 geom_sf 色彩美学(离散+连续)

r - 定期为 R Shiny 输出捕获 cat 输出(renderPrint)

r - 如何显示Shiny本地存储的多张图片(png)

r - 将不均匀数据时间 [时间戳] 系列转换为常规时间系列 : R

r - 如何向 geom_text 中的文本标签添加逗号分隔符?

r - Lattice中的facet_wrap相当于什么

r - 在 R 中使用 dplyr 的加权平均值进行汇总