如果有下面的情节。
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))
而不是蓝色,我想要一个渐变填充(从蓝色到红色垂直。因此,从底部的蓝色和顶部的红色开始,用一个参数来控制颜色变化的平滑性)。
我找到了以下资源:gradient.html
不幸的是,由于我的数据不是连续的(?)
发布于 2018-11-20 08:53:36
以下代码将执行此操作(但水平执行):
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))
如果您想使它垂直,您可以翻转坐标使用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))
或者,如果您希望它是水平的垂直梯度(如您所请求的那样),您可能需要使用您的数据并使用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))
这将给你以下几个方面:
希望你觉得这有帮助。
https://stackoverflow.com/questions/53397131
复制相似问题