gpt4 book ai didi

r - `geom_histogram` 和 `stat_bin()` 不对齐

转载 作者:行者123 更新时间:2023-12-04 19:25:42 33 4
gpt4 key购买 nike

构建直方图后,我想为我的绘图添加一个上边界/轮廓。我不想使用 geom_bargeom_col因为我不想要每个箱子的垂直边界。
我的尝试包括使用 geom_histogramstat_bin(geom = "bin") ,但是垃圾箱没有对齐。

我已经调整了每个几何图形中的参数( binsbinwidthcenterboundary )并且无法对齐这些分布。 SO ( Overlaying geom_points on a geom_histogram or stat_bin ) 上也有类似的问题,但似乎没有一个类似的问题需要挖掘或提供解决方案。

这是我的几何图层不对齐的情况:

set.seed(2019)
library(ggplot2)
library(ggthemes)
df <- data.frame(x = rnorm(100),
y = rep(c("a", "b"), 50))

p <- df %>%
ggplot(aes(x, fill = y)) +
geom_histogram() +
facet_wrap(vars(y)) +
theme_fivethirtyeight() +
guides(fill = F)

这是情节 p ,我的基本直方图:
enter image description here
p + stat_bin(geom = "step")

enter image description here

我想要一个这两个几何对齐的情节。我已经测试了各种虚拟数据,这仍然是一个问题。为什么这些几何图形不自然对齐?如何调整这些图层中的任何一个以对齐?有没有比结合直方图和统计箱更好的选择来实现我想要的情节?

最佳答案

条形图不会自然对齐,因为 geom_step 似乎使用每个直方图条形图的中间(x 返回的数据框中的 layer_data(p) 列)作为每个更改点的位置。因此,要对齐步骤,请使用 position_nudge 将 geom_step 移动 binwidth 的一半:

library(tidyverse)

p <- df %>%
ggplot(aes(x, fill = y)) +
geom_histogram(bins=20) +
facet_wrap(vars(y)) +
theme_fivethirtyeight() +
guides(fill = F)

binwidth = layer_data(p) %>% mutate(w=xmax-xmin) %>% pull(w) %>% median

p + stat_bin(geom = "step", binwidth=binwidth, position=position_nudge(x=-0.5*binwidth))

enter image description here

但是,请注意,在上图中,阶梯边框停止在左侧面板中最后一个条的中间,并且不限制右侧面板中第一个条的左边缘。以下是获取 geom_step 的技巧完全绑定(bind)所有直方图条。

我们在真实数据范围之外添加两行假数据,然后我们将绘图的 x 范围设置为仅包括真实数据的范围。在这种情况下,我设置了 binwidth (而不是 bin 的数量)因为扩展数据范围会增加任何固定数量的 bin 的 binwidth,并且还添加了 center参数,这不是必需的,但如果需要,可用于确保 bin 位于特定位置的中心。

如果这是您经常想要做的事情,您可以将其转换为具有某些逻辑的函数,以使用假数据自动扩展数据框并适本地设置图的 bin 和 x 范围。
p <- df %>% 
add_row(x=range(df$x) + c(-1,1), y="a") %>%
ggplot(aes(x, fill = y)) +
geom_histogram(binwidth=0.2, center=0) +
facet_wrap(vars(y)) +
theme_fivethirtyeight() +
guides(fill = F)

binwidth = layer_data(p) %>% mutate(xmax-xmin) %>% pull() %>% median

p +
stat_bin(geom = "step", binwidth=binwidth, position=position_nudge(x=-0.5*binwidth)) +
coord_cartesian(xlim=range(df$x[1:(nrow(df)-2)]) + c(-0.2,0.2))

enter image description here

这是没有额外行黑客的相同情节的样子:
p <- df %>% 
ggplot(aes(x, fill = y)) +
geom_histogram(binwidth=0.2, center=0) +
facet_wrap(vars(y)) +
theme_fivethirtyeight() +
guides(fill = F)

binwidth = layer_data(p) %>% mutate(xmax-xmin) %>% pull() %>% median

p +
stat_bin(geom = "step", binwidth=binwidth, position=position_nudge(x=-0.5*binwidth))

enter image description here

关于r - `geom_histogram` 和 `stat_bin()` 不对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014450/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com