R语言 如何在ggplot柱状图中添加误差线?

f87krz0w  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(190)

我想找出哪个城市有孩子的比例最高(是/否)。

> dput(df)
structure(list(City = c("Manhattan", "Los Angeles", "Manhattan", 
"Boston", "Dallas", "Los Angeles", "Dallas", "Los Angeles", "Dallas", 
"Manhattan", "Boston", "Manhattan"), Has_Kids = c(0L, 0L, 0L, 
1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, 
-12L))

现在我有代码来寻找平均值,但我还想添加误差线来查看任何显著的:

df %>%
  group_by(City) %>%
  dplyr::summarise(`Kids Percent` = 100 * mean(Has_Kids == 1)) %>%
  ggplot(aes(x = City, y = `Kids Percent`, fill = City)) +
  geom_text(
    aes(label = round(`Kids Percent`, 2)),
    vjust = -0.3,
    size = 2.5,
    na.rm = TRUE
  ) +
  geom_bar(stat = "identity", na.rm = TRUE) +
  theme_bw() +
  labs(title = "Kids by City [Proportion]",
       x = "City", y = "%") + theme(axis.text.x = element_text(
         angle = 90,
         vjust = 0.5,
         hjust = 1
       ))

编辑:我也对其他可能更好地可视化这些数据持开放态度。我的真实的数据集本质上是类似的,但我有大约200 k行。如果你知道任何更好的可视化方法,请推荐。

qxsslcnc

qxsslcnc1#

我没有足够高的声誉来评论,所以我被迫“回答”。
这类图(有时被称为炸药图,因为它们看起来像一个卡通式的炸药棒,里面有一根灯芯伸出来)并没有得到特别的重视,因为它们不能非常有效地传达数据的结构。
Dynamite Plots Mist Die为例,它包含一些替代项(在ggplot中)。

相关问题