简体   繁体   中英

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: 在此处输入图片说明

Do you have any idea how to do this?

Suggested solution using dplyr , tidyr and ggplot2 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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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