首页 > 解决方案 > ggplot直方图列内的线性颜色渐变

问题描述

我正在尝试用 ggplot2 重现这个情节:

在此处输入图像描述

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

我坚持这个线性颜色渐变,我不知道如何在每列中重现它。

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

但它已经很老了,我的数据看起来不太好,而且它更像是一种“分类着色”而不是“渐变着色”。

我还发现了这个:在渐变中绘制背景颜色,但它只在绘图背景上应用渐变,而不是在列中。

这可以使用 iris 数据集进行测试:

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

其中每个 Species 的 Petal.Width 值将用作直方图每列的着色渐变,并带有示例图中的颜色图例。

欢迎任何帮助!

标签: rggplot2

解决方案


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

关键是要有两个变量,一个用于着色(grad),另一个用于 x 轴(示例中的 x)。您需要使用desc()将较高的值放置在每个 bin 的较高位置。

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 包(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 包(v0.3.0)于 2020-05-14 创建


推荐阅读