【问题标题】:Color histogram by individual bins in ggplot2 rggplot2 r中各个bin的颜色直方图
【发布时间】:2020-09-29 01:14:52
【问题描述】:

我有一个由一系列直方图组成的图表。

为了强调直方图中所有 bin 的频率变化,我希望按各个 bin 的大小(即每个 bin 的“命中”数量)对其进行着色。我想创建一个热图效果,因此点击次数较多的 bin 与点击次数较少的 bin 的颜色不同。

与 bin 密度/命中相关的参数是什么?

干杯!

我当前的代码和我目前得到的代码: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```


【问题讨论】:

    标签: r ggplot2 histogram heatmap


    【解决方案1】:

    您要查找的参数是访问..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
    

    【讨论】: