我正在为条形图的子集创建一个条形图,我想添加错误条。

但是,我在用条形图排列错误栏时遇到了问题--我想让它们以每个条形图为中心。我该怎么做?此外,传说目前并没有明确区分条纹和非条纹的酒吧对应的不治疗和治疗组。
最后,我想创建这个地块的版本,它会堆叠相邻的条子(即每个facet_grid中的条形图),关于如何这样做的-any技巧将是非常感谢的。
我使用的代码是:
library(ggplot2)
library(tidyverse)
library(ggpattern)
models = c("a", "b")
task = c("1","2")
ratios = c(0.3, 0.4)
standard_errors = c(0.02, 0.02)
ymax = ratios + standard_errors
ymin = ratios - standard_errors
colors = c("#F39B7FFF", "#8491B4FF")
df <- data.frame(task = task, ratios = ratios)
df <- df %>% mutate(filler = 1-ratios)
df <- df %>% gather(key = "obs", value = "ratios", -1)
df$upper <- df$ratios + c(standard_errors,standard_errors)
df$models <- c(models,models)
df$lower <- df$ratios - c(standard_errors,standard_errors)
df$col <- c(colors,colors)
df$group <- paste(df$task, df$models, sep="-")
df$treated <- "yes"
df[df$ratios<0.5,]$treated = "no"
p <- ggplot(df, aes(x = group, y = ratios, fill = col, ymin = lower, ymax = upper)) +
stat_summary(aes(pattern=treated),
fun = "mean", position=position_dodge(),
geom = "bar_pattern", pattern_fill="black", colour="black") +
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2, position=position_dodge(0.9)) +
scale_pattern_manual(values=c("none", "stripe"))+ #edited part
facet_grid(.~task,
scales = "free_x", # Let the x axis vary across facets.
space = "free_x", # Let the width of facets vary and force all bars to have the same width.
switch = "x") + guides(colour = guide_legend(nrow = 1)) +
guides(fill = "none")
p发布于 2022-08-30 05:56:39
这里有一个选择
df %>%
ggplot(aes(x = models, y = ratios)) +
geom_col_pattern(
aes(fill = col, pattern = treated),
pattern_fill = "black",
colour = "black",
pattern_key_scale_factor = 0.2,
position = position_dodge()) +
geom_errorbar(
aes(ymin = lower, ymax = upper, group = interaction(task, treated)),
width = 0.2,
position = position_dodge(0.9)) +
facet_grid(~ task, scales = "free_x") +
scale_pattern_manual(values = c("none", "stripe")) +
scale_fill_identity()

几点意见:
group的意义。海事组织,这是不必要的。TBH,我也不明白models和task的意义:如果任务= "1“那么模型= "a";如果任务= "2”那么模型= "b";所以任务和模型是多余的,因为它们编码相同的东西(不管你叫它"1"/"2“还是”a“/”b“)。?scale_col_pattern,您可以使用pattern_key_scale_factor参数来调整这一点。在这里,我选择了pattern_key_scale_factor = 0.2,但您可能想使用不同的值。geom_errorbar不知道有不同的task-treated组合。我们可以通过显式定义group美学,通过task和treated值的组合来解决这个问题。您在aesthetic.data.frame.中定义了实际的颜色值,则您已经允许通过pattern使用treated值,希望使用scale_fill_identity()。
https://stackoverflow.com/questions/73516485
复制相似问题