Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create barplots for percentage values in r ggplot2

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading