繁体   English   中英

R - ggplot geom_histogram 下降值

[英]R - ggplot geom_histogram drops values

我在 ggplot 中绘制了一个极坐标直方图,但我遇到了一个问题:我似乎不能同时使用 plot 条,以便它们与各自的刻度线居中对齐并防止 ggplot 丢弃我的任何值.

屏幕截图说明了该问题。

可重现的例子:

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) 

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

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

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

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

然后,为了显示零 bin,我们实际上需要将x到 go 重新设置为 -5,因为 ggplot 正在查看它的全宽是否在 plot 区域中。

在这一点上,除了旋转之外,它看起来是正确的。 第一个 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)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM