如何使用 ggplot2 构建具有 2 组条形图的条形图:第一组用于每组的所有观察值;第二组符合标准的观察数量?

问题描述 投票:0回答:1

我有一张看起来像这样的桌子

tibble (person = c ("Paul", "Paul", "Paul", "Sarah", "Sarah", "Sarah", "Alex", "Alex", "Alex"),
    salary = c(8, 10, 3, 6, 6, 6, 1, 1, 3))

我将如何构建一个带有两组并排条形图的条形图,显示:

  1. 每人工资观察总数将给出条形 c(3, 3, 3)
  2. 工资高于 5 的观察数量将给出条形 c(2, 3, 0)
r ggplot2
1个回答
0
投票

我不建议尝试直接在 ggplot 中执行此操作。相反,您应该预先计算您的摘要并绘制它们:

library(tidyverse)

df <- tibble(person = c ("Paul", "Paul", "Paul", "Sarah", "Sarah", "Sarah", "Alex", "Alex", "Alex"),
              salary = c(8, 10, 3, 6, 6, 6, 1, 1, 3))

salary_counts <- df |> 
  summarize(
    total_salary = n(),
    high_salary = sum(salary > 5),
    .by = person
  ) |> 
  pivot_longer(cols = c(total_salary, high_salary), names_to = 'count_type', values_to = 'count')

salary_plot <- salary_counts |> 
  ggplot(data = _, aes(x = person, y = count, fill = count_type)) +
  geom_col(position = 'dodge')
print(salary_plot)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.