【问题标题】:Count and axis labels on stat_bin2d with ggplot使用 ggplot 在 stat_bin2d 上计数和轴标签
【发布时间】:2016-12-07 02:57:09
【问题描述】:

我正在尝试制作一个 2D 直方图,其中包含显示 bin 内容和梯度的各个 bin。数据是两个轴上从 0 到 4(仅)的整数。

我尝试使用this answer,但最终遇到了一些问题。首先,一些箱子最终根本没有梯度。在下面的 MWE 中,左下角的 130 和 60 似乎是空白的。其次,bin 在两个轴上都移动到 0 以下。对于这个轴问题,我发现我可以简单地在 x 和 y 上添加 0.5。最后,我还希望轴标签在 bin 内居中,并添加 0.5 并不能解决这个问题。

library(ggplot2)

# Construct the data to be plotted
x <- c(rep(0,190),rep(1,50),rep(2,10),rep(3,40))
y <- c(rep(0,130),rep(1,80),rep(2,30),rep(3,10),rep(4,40))
data <- data.frame(x,y)

# Taken from the example
ggplot(data, aes(x = x, y = y)) +
  geom_bin2d(binwidth=1) + 
  stat_bin2d(geom = "text", aes(label = ..count..), binwidth=1) + 
  scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
  xlim(-1, 5) +
  ylim(-1, 5) +
  coord_equal()

我在颜色渐变和轴标签中是否有明显的错误?如果有更好的方法来使用其他包/命令,我也没有与 ggplot 或 stat_bin2d 结婚。提前致谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    stat_bin2d 使用cut 函数来创建垃圾箱。默认情况下,cut 创建在左侧打开并在右侧关闭的 bin。 stat_bin2d 也设置了include.lowest=TRUE,这样最低的间隔也将在左边闭合。我还没有查看stat_bin2d 的代码来尝试找出到底出了什么问题,但这似乎与cut 中的breaks 的选择方式有关。在任何情况下,您都可以通过将 bin 中断显式设置为从 -1 开始来获得所需的行为。例如:

    ggplot(data, aes(x = x, y = y)) +
      geom_bin2d(breaks=c(-1:4)) + 
      stat_bin2d(geom = "text", aes(label = ..count..), breaks=c(-1:4)) + 
      scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
      xlim(-1, 5) +
      ylim(-1, 5) +
      coord_equal() 
    

    若要在整数格点上使瓦片居中,请将中断设置为半整数值:

    ggplot(data, aes(x = x, y = y)) +
      geom_bin2d(breaks=seq(-0.5,4.5,1)) + 
      stat_bin2d(geom = "text", aes(label = ..count..), breaks=seq(-0.5,4.5,1)) + 
      scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
      scale_x_continuous(breaks=0:4, limits=c(-0.5,4.5)) +
      scale_y_continuous(breaks=0:4, limits=c(-0.5,4.5)) +
      coord_equal()
    

    或者,为了强调这些值是离散的,将 bin 设置为半个单位宽:

    ggplot(data, aes(x = x, y = y)) +
      geom_bin2d(breaks=seq(-0.25,4.25,0.5)) + 
      stat_bin2d(geom = "text", aes(label = ..count..), breaks=seq(-0.25,4.25,0.5)) + 
      scale_fill_gradient(low = "snow3", high = "red", trans = "log10") + 
      scale_x_continuous(breaks=0:4, limits=c(-0.25,4.25)) +
      scale_y_continuous(breaks=0:4, limits=c(-0.25,4.25)) +
      coord_equal()
    

    【讨论】:

    • 完美!这是非常有用的。对此,我真的非常感激。干杯!
    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多