简体   繁体   English

在 R 中组合堆栈和分组条形图

[英]Combine stack and group bar chart in R

My data frame looks like:我的数据框看起来像:

year A B C
1983 1 2 10
1983 2 3 7
1984 1 3 7
1984 2 4 8
1985 1 6 6
1985 2 5 10

I would like to produce a bar chart grouping by A and showing the values of B as a subset of C, like this:我想生成一个按 A 分组的条形图,并将 B 的值显示为 C 的子集,如下所示: 在此处输入图片说明

Do you have any idea how to do this?你知道如何做到这一点吗?

Suggested solution using dplyr , tidyr and ggplot2 facet_ :使用dplyrtidyrggplot2 facet_建议解决方案:

df <- read.table(text='year A B C
    1983 1 2 10
    1983 2 3 7
    1984 1 3 7
    1984 2 4 8
    1985 1 6 6
    1985 2 5 10', header=TRUE, stringsAsFactors=FALSE)

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(cols = c(B, C)) %>% 
  ggplot(aes(factor(A), value, fill=factor(name, levels= c("C", "B")))) +
  geom_bar(stat="identity", position="stack") +
  facet_grid(~year) +
  labs(x="A", fill="Variable")

在此处输入图片说明

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

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