如何绘制堆积条形图使用R使用重复属性

时间:2017-04-29 09:02:37

标签: r bar-chart stacked

我的数据集有点像;

shell_exec()

我希望Age为我的X轴,对于Y轴,它应该显示男性和女性的数量,如堆积条形图。

有人可以帮我。 谢谢

1 个答案:

答案 0 :(得分:0)

# Load package
# package ggplot2 and dplyr are part of the tidyverse package
library(tidyverse)

# Create example data frame
dt <- read.csv(text = "Gender, Age, Count
female, 35, 1
male, 34, 2
male, 35, 1
male, 37, 2
female, 34, 2")

# Process the data frame, calcualte the total count of each gender and age combination
dt2 <- dt %>%
  group_by(Age, Gender) %>%
  summarise(Count = sum(Count))

# Plot the data use geom_bar, set stat = "identity"
ggplot(dt2, aes(x = Age, y = Count, fill = Gender)) +
  geom_bar(stat = "identity")

# Or you can use geom_col, which is the same
ggplot(dt2, aes(x = Age, y = Count, fill = Gender)) +
  geom_col()