r - 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 值将用作直方图每列的着色渐变,并带有示例图中的颜色图例。
欢迎任何帮助!
解决方案
由于未提供数据,我使用了一个玩具示例。
关键是要有两个变量,一个用于着色(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 创建
推荐阅读
- javascript - 在点击功能上运行 jQuery,但不在孩子上运行
- wordpress - 无法在 CodeMirror 编辑器中获取错误计数
- vue.js - 防止在每个输入/惰性输入上触发输入事件?
- android - Listview对android的涟漪效应
- bash - 如何将 bash 命令列表提供给 xargs 以并行运行?
- java - java中的可变变量强制一个线程从主内存中读取最新的副本,但在我的情况下它仍然不是
- java - Minecraft 1.8 Forge (javaw.exe) 一直卡在 Minecraft 的主启动器应用程序 (MinecraftLauncher.exe) 中
- db2 - DB2 的数据字典
- mongoose - Mongoose create() 为带有 Array 的模式提供“Cast to Array failed for value "[object Object],[object Object]"”
- wordpress - Wordpress:引导缓存文件每隔几周就会损坏一次