简体   繁体   English

如何在R中制作堆积条形图

[英]How to make a stacked bar plot in R

I have a data set that has information regarding 13 different teams (A:M).我有一个数据集,其中包含有关 13 个不同团队 (A:M) 的信息。 With each team, there is a variable for the total amount of people on each team, along with three different numeric variables for different characteristics measured.对于每个团队,每个团队的总人数都有一个变量,以及用于测量不同特征的三个不同数字变量。 The code below is an example of what I'm trying to work with:下面的代码是我正在尝试使用的示例:

Team <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M")
total <- c(557, 3, 3116, 201, 167, 1348, 877, 1444, 2, 1003, 25, 732, 2532)
characteristic1 <- c(111, 0, 566, 45, 77, 600, 356, 300, 0, 402, 3, 278, 312)
characteristic2 <- c(20, 0, 231, 14, 15, 27, 30, 78, 0, 48, 0, 29, 111)
characteristic3 <- c(1, 0, 29, 1, 0, 10, 11, 3, 0, 2, 9, 1, 3)

df <- data.frame(Team, total, characteristic1, characteristic2, characteristic3)

What I would like to do is make a stacked (or grouped) bar plot where x is each separate team.我想做的是制作一个堆叠(或分组)的条形图,其中 x 是每个单独的团队。 The largest bar on each team will be the total amount of people on each team.每个团队中最大的条将是每个团队的总人数。 And then I'd like to have stacked bars within each representing characteristic1, characteristic2, and characteristic3.然后我想在每个代表特征 1、特征 2 和特征 3 中堆叠条形。 I've also thought about doing each characteristic as a percentage of the total, but either way, I'm not sure how to go about making a bar plot to represent everything.我还考虑过将每个特征作为总数的百分比,但无论哪种方式,我都不确定如何制作条形图来代表所有内容。 I'd also be open to any suggestions of other ways to best represent this information that would not be in the form of a barplot.我也愿意接受任何其他方式的建议,以最好地表示这些信息,这些信息不会以条形图的形式出现。 Any help would be greatly appreciated!任何帮助将不胜感激!

Main feature is to bring your data in long format.主要功能是将您的数据以长格式提供。 The challenging thing here may be the total column.这里的挑战可能是总列。 But we could treat it just as another group member:但我们可以将其视为另一个组成员:

library(tidyverse)

df %>% 
  pivot_longer(-Team) %>%
  ggplot(aes(x=Team, y= value, fill = name)) +
  geom_col(position= position_dodge())

If you want a stacked bar then use position_stack() or position_fill() instead of position_dodge()如果你想要一个堆积条然后使用position_stack()position_fill()而不是position_dodge()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM