Home > Enterprise >  Create a stack bar chart, using r
Create a stack bar chart, using r

Time:01-06

I would like to create a stacked bar chart, in which stack all the bars into one by percentage. However, I can only create a normal bar chart. Seek for your help.

df$pecent <- paste0(round(100* group1$count/sum(group1$count)), "%")

ggplot(group1, aes(fuel_type, y= pecent, fill=pecent))   geom_bar(postion= position_stack(), stat="identity", show.legend = FALSE)

df: enter image description here

output: enter image description here

Many thanks

CodePudding user response:

This would be my approach with the mtcars data.

library(tidyverse)
mtcars %>%
  mutate(gear= as.factor(gear)) %>%
  group_by(gear) %>%
  tally() %>%
  ungroup %>%
  mutate(perc= n/sum(n),
         id="1") %>%
  ggplot(aes(x=id, y=perc, fill=gear)) 
  geom_col(position = "stack") 
  scale_y_continuous(labels= scales::percent)

Created on 2023-01-06 with reprex v2.0.2

CodePudding user response:

You could use x = "" with position = "fill" to stack all the values to one bar. To get a percentage axis you could use scale_x_continuous with percent labels. You can use the following code:

library(ggplot2)
ggplot(group1, aes(x = "", y= count, fill=fuel_type))   
  geom_bar(position="fill", stat="identity")  
  scale_y_continuous(labels= scales::percent)

Created on 2023-01-06 with reprex v2.0.2


Data:

group1 <- data.frame(fuel_type = c("DIESEL", "LPG", "PETROL", "PETROL/ELECTRIC"),
                 count = c(9,14,704,3),
                 pecent = c("1%", "2%", "96%", "0%"))

CodePudding user response:

Try this solution with str_extract to extract and convert to numeric the numeric values in column pecent:

library(stringr)
ggplot(group1, aes(x = "", 
                   y = as.numeric(str_extract(pecent, "\\d ")),
                   fill = fuel_type))  
  geom_bar(position = "stack", stat = "identity") 
  labs(y = "%", x = "")

Data (thanks to @Quinten):

group1 <- data.frame(fuel_type = c("DIESEL", "LPG", "PETROL", "PETROL/ELECTRIC"),
                 count = c(9,14,704,3),
                 pecent = c("1%", "2%", "96%", "0%"))
  • Related