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

时间:2016-10-27 12:09:19

标签: r ggplot2 histogram color-palette

我有一个简单的问题。如何使用固定ggplot2的{​​{1}}绘制直方图并填充彩虹色(或任何其他调色板)?

假设我有这样的数据:

binwidth

我想绘制直方图,使用例如myData <- abs(rnorm(1000)) 。然而,这将导致不同数量的箱子,具体取决于数据:

binwidth=.1

enter image description here

如果我知道箱子的数量(例如ggplot() + geom_histogram(aes(x = myData), binwidth=.1) ),我会使用类似的东西:

n=15

但随着垃圾箱数量的变化,我有点困在这个简单的问题上。

2 个答案:

答案 0 :(得分:5)

如果你真的想要灵活的数量,这是我的小解决方法:

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))

enter image description here

答案 1 :(得分:0)

如果binwidth是固定的,这里有一个替代解决方案,它使用内部函数ggplot2:::bin_breaks_width()在创建图形之前获取bin 的数量。这仍然是一种解决方法,但避免在the other solution中拨打geom_histogram()两次:

# 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)) 

enter image description here

作为第三种选择,聚合可以在ggplot2之外完成。然后,使用geom_col()代替geom_histogram()

# 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")

enter image description here

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