我有一张看起来像这样的桌子
tibble (person = c ("Paul", "Paul", "Paul", "Sarah", "Sarah", "Sarah", "Alex", "Alex", "Alex"),
salary = c(8, 10, 3, 6, 6, 6, 1, 1, 3))
我将如何构建一个带有两组并排条形图的条形图,显示:
我不建议尝试直接在 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)