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

5
我是一位能翻译文本的有用助手。

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

假设我有以下数据:

myData <- abs(rnorm(1000))

我想绘制直方图,例如使用 binwidth=.1。然而,这将导致不同数量的箱子,具体取决于数据:
ggplot() + geom_histogram(aes(x = myData), binwidth=.1) 

enter image description here

如果我知道箱子的数量(例如 n=15),我会使用以下代码:

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill=rainbow(n))

但是当箱子的数量变化时,我在这个简单问题上卡住了。


所以如果我理解你的意思正确的话,你希望直方图的每个条块根据彩虹渐变来着不同的颜色? - sebastian-c
是的,那正是我想要的。 - Art
@yup 同意... - user20650
为什么不直接通过“bins”参数强制指定箱子的数量呢? - Roman Luštrik
1
这似乎可以运行... n <- round(((max(myData)-min(myData))/.1)+1) - Rupert
显示剩余2条评论
2个回答

8

如果您希望垃圾桶数量更灵活,请看这个小技巧:

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


是的,那正是我需要的。我只是在想(并希望)有一种更直接的方法来做到这一点 :) 谢谢! - Art

4

如果binwidth是固定的,这里有一种替代方案,使用内部函数ggplot2:::bin_breaks_width()来获取在创建图表之前的bin数。虽然仍然是一个解决方法,但避免了像其他解决方案中两次调用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)) 

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

enter image description here

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

请注意,为了保持x轴连续,breaks被绘制在x轴上而不是levels(myData2)。否则,每个因子标签都会被绘制,从而使x轴变得混乱。还请注意,使用了内置的ggplot2颜色调色板,而不是rainbow()。图片链接:enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接