垂直渐变颜色与geom_area

时间:2017-06-10 17:34:53

标签: r ggplot2

我很难找到创建渐变色的解决方案 它应该是这样的(不要介意蓝色条)   enter image description here

类似于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))

1 个答案:

答案 0 :(得分:1)

由于geom_area无法进行渐变填充,因此这有点难度。

这里有一个非常hacky但可能是足够的选项,它可以制作一个栅格(但由于x和y尺寸不同而使用geom_tile)并且使用裁剪和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))

相关问题