【问题标题】:R - ggplot geom_histogram drops valuesR - ggplot geom_histogram 丢弃值
【发布时间】:2019-10-01 00:02:46
【问题描述】:

我正在 ggplot 中绘制一个极坐标直方图,但我遇到了一个问题:我似乎无法同时绘制条形图,以便它们与各自的刻度线居中对齐并防止 ggplot 丢弃任何我的价值观。

这个screenshot 说明了问题。

可重现的例子:

library(ggplot2)
data <- data.frame(b = c(0:360))
ggplot(data, aes(x = b)) +
  geom_histogram(binwidth = 10, fill = 'grey', color = 'black') +
  scale_x_continuous(breaks=seq(0, 270, by=90), limits = c(0, 360)) +
  coord_polar(start = 0) 

我收到此消息,但 360° 的栏不见了:

Warning message:
Removed 2 rows containing missing values (geom_bar). 

如果我添加一个边界输入,所有的条都会出现,并且不会删除任何值。但是,条形现在相对于它们的刻度线左对齐,而不是居中对齐。

ggplot(data, aes(x = b)) +
  geom_histogram(binwidth = 10, boundary = 0, fill = 'grey', color = 'black') +
  scale_x_continuous(breaks=seq(0, 270, by=90), limits = c(0, 360)) +
  coord_polar(start = 0) 

最终,如何确保条形图保持居中对齐而不是左对齐而不丢失任何值?

【问题讨论】:

  • 你的数据是 361 宽的,这是故意的吗?这不会平均分成 10 个桶。
  • 是的,这是故意的,0/360 处的栏会更长一些。

标签: r ggplot2 histogram polar-coordinates


【解决方案1】:

这需要一些摆弄。好奇我是否遗漏了一些 ggplot 选项来简化这一点。

首先,您似乎希望 b == 0:9b == 360 位于“0”箱中。 geom_histogram 想要绘制以 5 为中心的那些,因此要使该 bin 以 0 为中心,一种选择是手动将值移动 5。(参见下面的 data$c。)

然后,我想确保新的 -5 到 +4 数据在零组中被分箱,所以我切换了closed = "left"

然后,为了显示零仓,我们实际上需要 x 回到 -5,因为 ggplot 正在查看它的全宽是否在绘图区域内。

此时,除了旋转之外,它看起来是正确的。第一个 bin 的左边缘在 12 点钟方向。为了让它的中心在那里对齐,我们需要将整个东西移动-pi/36

data <- data.frame(b = c(0:360))
data$c <- (data$b %% 360) - 5
ggplot(data, aes(x = c)) +
  geom_histogram(binwidth = 10, boundary = 5, fill = 'grey', color = 'black', 
                 closed = "left") +
  scale_x_continuous(breaks=seq(0, 270, by=90), limits = c(-5, 355)) +
  coord_polar(start = -pi/36) 

替代解决方案

如果你不喜欢geom_histogram,我发现先求和然后切换到geom_col 会更简单:

sum_data <- data %>% dplyr::count(grp = (floor(b/10)*10) %% 360)
ggplot(sum_data, aes(grp, n)) +
  geom_col(fill = 'grey', color = 'black') +
  scale_x_continuous(breaks=seq(0, 270, by=90), limits = c(-5, 355)) +
  coord_polar(start = -pi/36)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多