渐变填充ggplot2

时间:2018-11-20 16:13:29

标签: r ggplot2

说是否有以下情节。

library(ggplot2)
n <- 1169
df22 <- data.frame(x = 1:n, val = seq(0, 0.5, length.out = n), type = 1)

ggplot(df22, aes(x = x, y = val)) +
  geom_ribbon(aes(ymax = val, ymin = 0, fill = type, group = type))

我想用蓝色(而不是蓝色)填充渐变(垂直从蓝色到红色。所以从底部的蓝色开始,从顶部的红色开始,使用一个参数来控制颜色变化的平滑度)。

我找到了以下资源: https://ggplot2.tidyverse.org/reference/scale_gradient.html

不幸的是,由于我的数据不连续(?),它对我没有效果。

1 个答案:

答案 0 :(得分:6)

以下代码可以做到(但水平):

library(scales) # for muted
ggplot(df22, aes(x = x, y = val)) +
  geom_ribbon(aes(ymax = val, ymin = 0, group = type)) +
  geom_col(aes(fill = val)) +
  scale_fill_gradient2(position="bottom" , low = "blue", mid = muted("blue"), high = "red", 
                       midpoint = median(df22$val)) 

Ribbon-Horizontally

如果要垂直放置,可以使用coord_flip()上下翻转坐标。

ggplot(df22, aes(x = val, y = x)) +
  geom_ribbon(aes(ymax = val, ymin = 0)) +
  coord_flip() +
  geom_col(aes(fill = val)) +
  scale_fill_gradient2(position="bottom" , low = "blue", mid = muted("blue"), high = "red", 
                       midpoint = median(df22$val)) 

Ribbon-Vertically

或者,如果您希望它按水平方向垂直倾斜(按您的要求),则可能需要通过处理数据并使用geom_segment()而不是geom_ribbon()来解决它,类似于以下内容:

vals <- lapply(df22$val, function(y) seq(0, y, by = 0.001))
y <- unlist(vals)
mid <- rep(df22$x, lengths(vals))
d2 <- data.frame(x = mid - 1, xend = mid + 1, y = y, yend = y)

ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
  geom_segment(size = 1) +
  scale_color_gradient2(low = "blue", mid = muted("blue"), high = "red", midpoint = median(d2$y)) 

这将为您提供以下内容:

enter image description here

希望对您有所帮助。