gpt4 book ai didi

r - 通过垂直分割垃圾箱,通过精确的截止点为 ggplot 直方图着色

转载 作者:行者123 更新时间:2023-12-05 05:11:10 26 4
gpt4 key购买 nike

我想通过不同的垂直截止点为 ggplot 直方图着色。我能够使用 this answer ,但发现在我的数据中,箱子被分开并缩短了。下面的最小示例和图表。

如何在不将这些切碎的较短垃圾箱垂直拆分的情况下将垃圾箱分开?

library(tidyverse)

set.seed(42)

# define cutoffs
cutoff_1 <- -21
cutoff_2 <- 60

df <- data.frame(rand = rnorm(10000)*100) %>%
mutate(colors = case_when(
rand < cutoff_1 ~ "red",
rand >= cutoff_1 & rand <= cutoff_2 ~ "blue",
rand > cutoff_2 ~ "green"
)
)
n.bins <- 20 # number of bins
additional.cutoffs <- c(cutoff_1, cutoff_2) # additional bins

bins <- seq(min(df$rand), max(df$rand), length.out = n.bins)
bins <- c(bins, additional.cutoffs) %>% sort()

df %>%
ggplot(aes(x=rand, fill=colors)) +
geom_histogram(breaks=bins) +
geom_vline(xintercept=c(cutoff_1, cutoff_2), colour="black")

enter image description here

最佳答案

我能想到的一种方法是将截断作为大小相等的垃圾箱的边界。一种方法是:

# decide bin width (I decided to have two bins in the middle)
binwidth <- (cutoff_2 - cutoff_1)/2
# create a possible bins (stating from the cut off and make sure that it covers the domain
bins <- -21 + (-15:15) * binwidth
# limit the range of possible bins based on the range of the data
bins <- bins[between(bins, min(df$rand) - binwidth, max(df$rand) + binwidth)]

df %>%
ggplot(aes(x=rand, fill=colors)) +
geom_histogram(breaks=bins) +
geom_vline(xintercept=c(cutoff_1, cutoff_2), colour="black") + theme_minimal()

enter image description here

注意事项

但我可能会说,做这样的事情看起来是一种更自然的数据呈现方式。

Fill different colors for each quantile in geom_density() of ggplot

关于r - 通过垂直分割垃圾箱,通过精确的截止点为 ggplot 直方图着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724880/

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