ggplot2 r 中各个 bin 的颜色直方图

Color histogram by individual bins in ggplot2 r

我有一个图表,它是一系列直方图。

为了强调直方图中所有 bin 的频率变化,我希望根据大小(即每个 bin 的 'hits' 的数量)为各个 bin 着色。我想创建热图效果,因此点击次数较多的箱子与点击次数较少的箱子颜色不同。

与 bin density/hits 关联的参数是什么?

干杯!

我当前的代码和我目前得到的:https://i.stack.imgur.com/fZcQb.png

  ggplot( aes(y=branchAngle, color=DBH, fill=DBH)) +
  geom_histogram(alpha=1, binwidth = 0.1, size = .1) +
  scale_fill_viridis(discrete=FALSE) +
  scale_color_viridis(discrete=FALSE) +
  theme_ipsum() +
  theme(
    panel.spacing = unit(0.1, "lines"),
    strip.text.x = element_text(size = 8),
    axis.line = element_line(colour = "black"),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank()
  ) +
  xlab("") +
  ylab("Branch Angle") +
  scale_y_continuous(breaks=seq(0,90,30)) +
  facet_wrap(~factor(DBH), ncol = 16)


p```


您要查找的参数是访问 ..count.. 作为来自 stat_bin() 的内部计算数字。您也可以使用 ..density..,具体取决于您的喜好。下面是一些示例:

library(ggplot2)
library(tidyr)
library(dplyr)

# dataset
set.seed(1234)
df <- data.frame(
  Group1=rnorm(1000, 50, 50),
  Group2=rnorm(1000, 35,67),
  Group3=rnorm(5000, 57,40),
  Group4=rnorm(1000, 75, 60)
)
df <- df %>% gather(group, value)

# plot 1
p <- ggplot(df, aes(x=value)) +
  geom_histogram(aes(fill=group, alpha=..count..), bins=50) +
  facet_grid(.~group) + coord_flip() + theme_classic()
p

如果你想使用填充美学,这里有一个例子:

p1 <- ggplot(df, aes(x=value)) +
  geom_histogram(aes(fill=..count..), bins=50) +
  facet_grid(.~group) + coord_flip() + theme_classic() +
  scale_fill_gradient(low='yellow', high='red')
p1