【问题标题】:Vertical gradient color with geom_area [duplicate]带有geom_area的垂直渐变颜色[重复]
【发布时间】:2017-11-12 13:22:31
【问题描述】:

我很难找到创建渐变颜色的解决方案。
这就是它的样子(不要介意蓝色条)

类似于How to make gradient color filled timeseries plot in R 的东西,但对我来说要重用这个例子有点高级。我没有任何负值,最大值为 80。我尝试了nograpes 提供的答案,我的电脑被冻结了大约 6-7 分钟,然后我收到消息:
Error in rowSums(na) : 'Calloc' could not allocate memory (172440001 of 16 bytes)

这只是具有 841 行(一些包含 NA)的数据子集,之前答案中的解决方案对我几乎不起作用。

    df <- structure(list(date = structure(c(1497178800, 1497182400, 1497186000, 
1497189600, 1497193200, 1497196800, 1497200400, 1497204000, 1497207600, 
1497211200, 1497214800, 1497218400, 1497222000, 1497225600, 1497229200, 
1497232800, 1497236400, 1497240000, 1497243600, 1497247200, 1497250800, 
1497254400, 1497258000, 1497261600, 1497265200, 1497268800, 1497272400, 
1497276000, 1497279600, 1497283200, 1497286800, 1497290400, 1497294000, 
1497297600, 1497301200, 1497304800, 1497308400, 1497312000, 1497315600, 
1497319200, 1497322800, 1497326400, 1497330000, 1497333600, 1497337200, 
1497340800, 1497344400, 1497348000, 1497351600, 1497355200), class = c("POSIXct", 
"POSIXt"), tzone = "UTC"), dk_infpressure = c(22, 21.6, 21.2, 
20.9, 20.5, 20.1, 19.8, 19.4, 19, 18.6, 18.2, 17.9, 17.5, 17.1, 
16.8, 16.4, 16, 15.6, 15.2, 14.9, 14.5, 14.1, 13.8, 13.4, 13, 
12.5, 11.9, 11.4, 10.8, 10.3, 9.8, 9.2, 8.7, 8.1, 7.6, 7, 6.5, 
6, 5.4, 4.9, 4.3, 3.8, 3.2, 2.7, 2.2, 1.6, 1.1, 0.5, 0, 0)), .Names = c("date", 
"dk_infpressure"), row.names = c(NA, -50L), class = c("tbl_df", 
"tbl", "data.frame"))

获取基本情节的代码:

 ggplot()+
geom_area(data=df, aes(x = date, y= dk_infpressure ) )+
scale_y_continuous(limits = c(0, 80))

【问题讨论】:

  • 您希望我们为您编写代码吗?因为答案已经存在,您只需要修改以适用于日期时间对象。
  • 我已对问题进行了更改。请告诉我是否可以做更多事情以使其更清楚。

标签: r ggplot2


【解决方案1】:

因为geom_area不能进行渐变填充,所以这个问题有点难。

这是一个绝对 hacky 但可能足够的选项,它可以制作光栅(但使用 geom_tile,因为 x 和 y 大小不同)并用裁剪和 ggforce::geom_link 覆盖参差不齐的边缘(geom_segment 的一个版本,可以绘制渐变):

library(tidyverse)

df %>% 
    mutate(dk_infpressure = map(dk_infpressure, ~seq(0, .x, .05))) %>%    # make grid of points
    unnest() %>% 
    ggplot(aes(date, dk_infpressure, fill = dk_infpressure)) + 
    geom_tile(width = 3600, height = 0.05) + 
    # hide square tops
    ggforce::geom_link(aes(color = dk_infpressure, xend = lag(date), yend = lag(dk_infpressure)), 
                       data = df, size = 2.5, show.legend = FALSE) + 
    scale_x_datetime(expand = c(0, 0)) +    # hide overplotting of line
    scale_y_continuous(expand = c(0, 0))

【讨论】:

  • 感谢@alistaire!我有几个问题:当我在我的真实数据上运行它时,它给了我错误:Error in seq.default(0, .x, 0.05) : 'to' must be a finite number。如何将颜色更改为黄色和红色渐变? ylab可以固定在80吗?
  • 该错误可能是因为dk_infpressure 中的NA 值。由于它无论如何都不会绘制,因此您可以在绘制之前在整个 data.frame 上调用na.omittidyr::drop_na。要更改渐变,请使用 scale_fill_gradientscale_color_gradient(或等效项)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
相关资源
最近更新 更多