如何用颜色渐变填充直方图? [英] How to fill histogram with color gradient?
本文介绍了如何用颜色渐变填充直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
binwidth
绘制直方图并用彩虹色(或任何其他调色板)填充<?c $ c> ggplot2 ? 可以说我有这样的数据:
myData< ; - abs(rnorm(1000))
我想绘制直方图,使用eg binwidth = 0.1
。然而,这将导致不同数量的垃圾箱,这取决于数据:
ggplot()+ geom_histogram(aes(x = myData), binwidth = .1)
如果我知道垃圾箱数目(例如 n = 15
),我会使用类似于:
ggplot()+ geom_histogram(aes(x = myData),binwidth = .1,fill = rainbow(n))
但随着垃圾箱数量的不断变化,我陷入了这个简单问题。
解决方案
如果你真的想要灵活的箱子数量,这是我的小解决方法:
library(ggplot2)
gg_b< - ggplot_build(
ggplot()+ geom_histogram(aes(x = myData), bin)= b1 bb
nu_bins < - dim(gg_b $ data [[1]])[1]
ggplot()+ geom_histogram( aes(x = myData),binwidth = .1,fill = rainbow(nu_bins))
I have a simple problem. How to plot histogram with ggplot2
with fixed binwidth
and filled with rainbow colors (or any other palette)?
Lets say I have a data like that:
myData <- abs(rnorm(1000))
I want to plot histogram, using e.g. binwidth=.1
. That however will cause different number of bins, depending on data:
ggplot() + geom_histogram(aes(x = myData), binwidth=.1)
If I knew number of bins (e.g. n=15
) I'd use something like:
ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill=rainbow(n))
But with changing number of bins I'm kind of stuck on this simple problem.
解决方案
If you really want the number of bins flexible, here is my little workaround:
library(ggplot2)
gg_b <- ggplot_build(
ggplot() + geom_histogram(aes(x = myData), binwidth=.1)
)
nu_bins <- dim(gg_b$data[[1]])[1]
ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill = rainbow(nu_bins))
这篇关于如何用颜色渐变填充直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文