ggplot直方图列内的线性颜色渐变

时间:2020-05-14 11:10:03

标签: r ggplot2

我正在尝试使用ggplot2复制此图:

enter image description here

据我了解,您可以将其称为具有线性颜色渐变的直方图

我坚持使用这种线性颜色渐变,无法确定如何在每列中重现它。

我在这里找到另一篇文章的解决方法:Trying to apply color gradient on histogram in ggplot

但是它是一个很旧的并且不能很好地显示我的数据,而且它更像是一种“分类着色”而不是“渐变着色”。

我也发现了这一点:Plot background colour in gradient,但它仅将梯度应用于绘图背景,而不应用于列。

可以使用虹膜数据集进行测试:

ggplot(iris, aes(x=Species, fill=Petal.Width)) +
    geom_histogram(stat = "count")

每个物种的Petal.Width值将用作带有示例颜色的直方图的每一列的着色渐变,如示例图所示。

欢迎任何帮助!

1 个答案:

答案 0 :(得分:3)

由于未提供数据,因此我使用一个玩具示例。

重点是要有两个变量,一个用于着色(渐变),另一个用于x轴(在示例中为x)。您需要使用desc()来将较高的值放在每个容器的较高位置。

library(tidyverse)

n <- 10000
grad <- runif(n, min = 0, max = 100) %>% round()
x <- sample(letters, size = n, replace = T)

tibble(x, grad) %>%
ggplot(aes(x = x, group = desc(grad), fill = grad)) + 
geom_bar(stat = 'count') + 
scale_fill_viridis_c()

reprex package(v0.3.0)于2020-05-14创建

或者,使用iris,示例如下:

library(tidyverse)
ggplot(iris, aes(x=Species, group = desc(Petal.Width), fill=Petal.Width)) +
geom_histogram(stat = "count") + 
scale_fill_viridis_c()
#> Warning: Ignoring unknown parameters: binwidth, bins, pad

reprex package(v0.3.0)于2020-05-14创建