【问题标题】:Error filling and distributing values on the x-axis of the bar graph在条形图的 x 轴上填充和分布值时出错
【发布时间】:2022-11-03 00:41:15
【问题描述】:

我正在尝试在 ggplot 中创建一个条形图,考虑填充每个条形的“类型”变量。

但是,条形图的最大值过高(高于 100,而实际上它们应该接近 40)。我的目标是放置覆盖填充。

我很感激任何帮助。

df <- structure(list(Count = c("Beu", "Beu", "Beu", "Abe", "Abe", "Abe", 
"Pre", "Pre", "Pre", "Bra", "Bra", "Bra"), Type = c(1, 2, 3, 
1, 2, 3, 1, 2, 3, 1, 2, 3), Hours = c(40.17775, 42.1492178098676, 
42.1910353866317, 38.3701812919564, 39.9185282522996, 38.8002722361139, 
41.6389448017412, 41.7041742286751, 41.9545826200271, 41.1375910844406, 
41.0602923264312, 40.6300999927013)), row.names = c(NA, 12L), class = "data.frame")

这是我要运行的代码:

df %>% 
  mutate(Type = as.factor(Type)) %>% 
  ggplot(mapping = aes(x = Count, y = Hours, fill = Type)) +
  geom_bar(stat = 'identity') +
  coord_flip() +
  theme_classic()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    要覆盖条形,您可以在 geom_bar 中添加 position = 'identity',并使用较低的透明度 alpha,如下所示:

    library(ggplot2)
    library(dplyr)
    df %>% 
      mutate(Type = as.factor(Type)) %>% 
      ggplot(mapping = aes(x = Count, y = Hours, fill = Type)) +
      geom_bar(stat = 'identity', position = 'identity', alpha =0.2) +
      coord_flip() +
      theme_classic()
    

    创建于 2022-11-02,reprex v2.0.2

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2016-01-15
      • 1970-01-01
      • 2021-12-19
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多