Home > Back-end >  Stacked barplot from already calculated counts
Stacked barplot from already calculated counts

Time:09-26

This is probably too easy but I failed to find an answer online.

I have a table that already counted the number of the variables (i.e. number of questions answered true and number of questions answered false)

dfr = data.frame(class=c("true", "false"), count=c(20,80))

how do I create a barplot that displays these numbers in one stacked barplot ? something like this enter image description here

all the methods are found online deal with a dataframe rather than a table of pre calculated counts.

image was taken from this question: enter image description here

CodePudding user response:

Using the barplot function that comes with R.

## basic
barplot(as.matrix(dfr$count), horiz=TRUE, legend.text=dfr$class)


## refined a little
barplot(as.matrix(dfr$count), horiz=TRUE, col=c('#1F77B4', '#FF7F0E'), legend.text=dfr$class, ylim=c(0, 2))
box()

enter image description here

CodePudding user response:

With a bit of pre-processing to the data to get the values and variables you need for plotting and fiddling about with ggplot you could try:

library(ggplot2)
library(dplyr)
library(forcats)

dfr <- data.frame(class=c("true", "false"), count=c(20,80))

df2 <- 
  dfr|>
  arrange(desc(count))|>
  mutate(class = fct_inorder(class),
         y = "R1",
         label = cumsum(count))


ggplot(df2, aes(count, y, fill = fct_rev(class))) 
  geom_col() 
  geom_text(aes(label = count, x =  label), hjust = 1.2) 
  scale_x_continuous(expand = expansion(mult = c(0, 0.05))) 
  scale_y_discrete(expand = expansion(mult = c(0.8))) 
  scale_fill_manual(values = c("coral", "cornflowerblue"),
                    breaks = c("true", "false"),
                    labels = c("Yes", "No")) 
  labs(x = NULL,
       y = NULL,
       fill = NULL) 
  theme_bw() 
  theme(panel.grid = element_blank(),
        legend.position = c(0.90, 0.91),
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey"),
        legend.margin=margin(t=0,l=1,b=1,r=1, unit='mm'))

Created on 2022-09-25 with reprex v2.0.2

  • Related