【问题标题】:Obtain two barplots in the same graph ggplot2在同一个图中获取两个条形图ggplot2
【发布时间】:2023-01-19 23:22:35
【问题描述】:

我有两个数据框:

df1 <- data.frame(name = rep(LETTERS[1:5], each = 5), age = 1:25)
df2 <- data.frame(name = rep(LETTERS[1:5], each = 5), age = c(rep(1,5), rep(5,5), 1,12,3,2,1,1:5,6:10))

我想制作这样的水平条形图:

df1 %>%
  mutate(name = fct_reorder(name, age)) %>%
  ggplot( aes(x = name, y = age)) +
  geom_bar(stat = "identity", fill = "#74D055FF", alpha = .6, width = .6) +
  coord_flip() +
  theme_bw()

df2 %>%
  mutate(name = fct_reorder(name, age)) %>%
  ggplot( aes(x = name, y = age)) +
  geom_bar(stat = "identity", fill = "#481568FF", alpha = .6, width = .6) +
  coord_flip() +
  theme_bw()

我想在同一张图中显示它们:age = 0应该有一条垂直线,然后紫色条应该在一侧,绿色条在另一侧(当然它只会被排序基于 df1df2age,因为 age 的降序在两个数据帧中不同)。我不知道这种类型的情节如何称呼以及如何处理。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    一种选择是将您的数据集绑定到一个数据框中,并添加一个我使用 dplyr::bind_rows 的标识符列。然后可以将标识符映射到fill aes 和通过scale_fill_manual 设置的颜色。我还使用 count 聚合了数据,而不是依赖于堆叠:

    library(dplyr)
    library(ggplot2)
    
    dplyr::bind_rows(df1, df2, .id = "id") %>%
      count(id, name, wt = age, name = "age") |>
      mutate(
        name = reorder(name, (id == 1) * age, sum),
        age = if_else(id == 2, -age, age)
      ) |>
      ggplot(aes(y = name, x = age, fill = id, group = 1)) +
      geom_col(alpha = .6, width = .6) +
      geom_vline(xintercept = 0) +
      scale_fill_manual(values = c("#74D055FF", "#481568FF")) +
      theme_bw()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 2022-12-03
      相关资源
      最近更新 更多