简体   繁体   中英

Bar plot for multiple category grouped variables

I am new to R and I want to plot bar plots for multiple categories of data derived from another table. I am trying to use ggplot() but don't quite know how to create segmented bar plots using it.

I have a data frame on a number of students who answered specific questions on a test across different sections. The total number of questions for each section is also different. The data looks something like this.

I want to construct a segmented bar plot with each section as the x-axis and values of each row stacked one upon the other (with labels).

Any help would be much appreciated!

  Section Neither.1.nor.2 Only.1 Only.2 Both.1.2
1       A              12      5      3        6
2       B              55     15      2       26
3       C              17     27     18       33
4       D              31     32     56       12

With your data (please, next time, copy and past the output from dput(yourdata) ):

library(tidyverse)

tib <- tibble(
  Section           = LETTERS[1:4],
  'Neither 1 nor 2' = c(12, 55, 17, 31),
  'Only 1'          = c(5, 15, 27, 32),
  'Only 2'          = c(3, 2, 18, 56),
  'Both 1 & 2'      = c(6, 26, 33, 12)
)

We can do it this way (upd):

tib %>%
  gather(key = 'Category', value = 'Value', -Section) %>% 
  mutate(Category = factor(Category, unique(Category))) %>%
  ggplot(aes(x = Section, y = Value, fill = Category, label = Value)) +
  geom_bar(position = 'stack', stat = 'identity') +
  geom_text(position = 'stack', vjust = 1.5, colour = 'gray25', size = 2) +
  scale_fill_brewer(type = 'qual', palette = 'Accent') #+
  #ggthemes::theme_tufte()

条形图

But it would be better to set show.legend = T and remove text labels.

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