Home > OS >  Create barplots for percentage values in r ggplot2
Create barplots for percentage values in r ggplot2

Time:12-15

I have a dataframe with several categorical values, let's say the Arthritis dataset from vcd package.

## Load vcd package
library(vcd)

## Load Arthritis dataset (data frame)
data(Arthritis)  

colnames(Arthritis)
"ID" "Treatment" "Sex" "Age" "Improved"

I want to create a barplot of the counts for the treatment (x axis with placebo and treated) for those patients which improved. This is the code:

Arthritis1 <- Arthritis %>%
  dplyr::filter(Improved == "Marked") 

ggplot(data = Arthritis1, aes(x = Treatment))   
  geom_bar()

However, now I want to plot the percentages. That is, for all the patients with placebo, the percentage of those belonging to "Marked" improvement. And for all the "treated" patients the percentage of those belonging to "Marked" improvement.

I can get the percentages like this.

a = table(Arthritis1$Treatment)[1]/table(Arthritis$Treatment)[1]
b = table(Arthritis1$Treatment)[2]/table(Arthritis$Treatment)[2]

Arthritis2 <- as.data.frame(c(a, b)) 
colnames(Arthritis2)[1] <- "var1"

str(Arthritis2)
'data.frame':   2 obs. of  1 variable:
 $ var1: num  0.163 0.512

So I would want a plot with two columns, with the value 1 as a top, Placebo reaching to 0.163 and Treated reaching to 0.512.

However I, didn't find a way yet of plotting this as a percentage, as geom_bar() for example, plots the counts.

CodePudding user response:

You need geom_bar(stat = "identity") if you have already calculated the percentages:

library(tidyverse)
library(vcd)
#> Loading required package: grid
data(Arthritis)

Arthritis %>%
  filter(Improved == "Marked") %>%
  count(Treatment) %>%
  mutate(n = n / sum(n) * 100) %>%
  ggplot(aes(Treatment, n))   
    geom_bar(stat = "identity")  
    labs(y = "Percentage")

Created on 2021-12-15 by the reprex package (v2.0.1)

  • Related