渐变填充ggplot2 [英] Gradient fill in ggplot2

查看:143
本文介绍了渐变填充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))

我希望使用蓝色(而不是蓝色)填充颜色(垂直从蓝色到红色.所以从底部开始是蓝色,顶部是红色,并带有一个用于控制颜色变化平滑度的参数).

Instead of the blue color i would like to have a Gradient fill (from blue to red - vertically. So starting with blue at the bottom and red on top with a Parameter to Control the smoothness of Color change).

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

I found the following resource: https://ggplot2.tidyverse.org/reference/scale_gradient.html

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

Unfortunately, it didnt work out for me as my data is not continous(?).

推荐答案

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

The following code will do it (but horizontally):

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()上下翻转坐标.

If you want to make it vertically, you may flip the coordinates using coord_flip() upside down.

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()来解决它,如下所示:

Or, if you want it to be horizontal with a vertical gradient (as you requested), you might need to go around it by playing with your data and using the geom_segment() instead of geom_ribbon(), like the following:

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)) 

这将为您提供以下内容:

This will give you the following:

希望对您有帮助.

这篇关于渐变填充ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆