R 如何用颜色渐变填充直方图?

R 如何用颜色渐变填充直方图?,r,ggplot2,histogram,color-palette,R,Ggplot2,Histogram,Color Palette,我有一个简单的问题。如何使用固定的binwidth和彩虹色(或任何其他调色板)绘制直方图 假设我有这样一个数据: myData <- abs(rnorm(1000)) 如果我知道垃圾箱的数量(例如,n=15),我会使用类似于: ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill=rainbow(n)) 但随着垃圾箱数量的变化,我有点陷入了这个简单的问题 如果您真的希望垃圾箱的数量灵活,下面是我的小解决方法: lib

我有一个简单的问题。如何使用固定的
binwidth
和彩虹色(或任何其他调色板)绘制直方图

假设我有这样一个数据:

myData <- abs(rnorm(1000))

如果我知道垃圾箱的数量(例如,
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), binwidth=.1)
)

nu_bins <- dim(gg_b$data[[1]])[1]

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill = rainbow(nu_bins))
库(ggplot2)

gg_b如果binwidth是固定的,这里有一个替代解决方案,它使用内部函数
ggplot2:::bin_breaks_width()
在创建图形之前获取bin的数量。这仍然是一个解决方法,但避免调用
geom\u histogram()
两次,如:


请注意,
中断
绘制在x轴上,而不是
级别(myData2)
以保持x轴连续。否则,将绘制每个因子标签,这将使x轴混乱。另外请注意,使用内置的
ggplot2
调色板,而不是
rainbow()

,因此,如果我理解正确,您希望直方图的每个单元根据彩虹渐变的不同颜色?是的,这正是我想要的want@user20650我看到这个答案,,但那边的垃圾箱数量是固定的,所以这并不能解决我的问题。@yup同意……这似乎有效<是的,这正是我需要的。我只是在想(并希望)有更直接的方法来做到这一点:)谢谢!
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))
# create sample data
set.seed(1L)
myData <- abs(rnorm(1000))
binwidth <- 0.1

# create plot    
library(ggplot2)   # CRAN version 2.2.1 used
n_bins <- length(ggplot2:::bin_breaks_width(range(myData), width = binwidth)$breaks) - 1L
ggplot() + geom_histogram(aes(x = myData), binwidth = binwidth, fill = rainbow(n_bins)) 
# start binning on multiple of binwidth
start_bin <- binwidth * floor(min(myData) / binwidth)
# compute breaks and bin the data
breaks <- seq(start_bin, max(myData) + binwidth, by = binwidth)
myData2 <- cut(sort(myData), breaks = breaks, by = binwidth)

ggplot() + geom_col(aes(x = head(breaks, -1L), 
                        y = as.integer(table(myData2)), 
                        fill = levels(myData2))) + 
  ylab("count") + xlab("myData")