Home > Mobile >  how to draw a histogram using categorical varibles as y in R
how to draw a histogram using categorical varibles as y in R

Time:09-01

I have some data and wanna draw a histogram like this picture using R.

My data is:

 MCV   mortality
 100   0
 100   1
  90   1
  70   1
  70   0

I only want to show that mortality == 1 as proportion in y-axis. I found some code but not exact what I need:

ggplot(data=t, aes(MCV, fill=mortality))   
  geom_histogram(aes(y=c(..count..[..group..==1]/sum(..count..))),
                    
                 position='dodge', binwidth=5)  
  ylab("Percentage")  xlab("MCV")

Can someone give me some hints?

enter image description here

CodePudding user response:

Not quite sure what you need exactly, but maybe this will do the job?

library(dplyr)
library(ggplot2)

dt <- t %>% 
  mutate(MCV_cut = cut(MCV, c(-Inf,70,80,90,100,Inf), c("<70", paste(c(70,80,90), c(80,90,100), sep = "-"), ">=100"), right = FALSE)) %>% 
  group_by(MCV_cut) %>% 
  summarise(mortality_perc = sum(mortality) / n()) %>% 
  ungroup()

ggplot(dt)  
  geom_line(aes(x = MCV_cut, y = mortality_perc, group = NA))

CodePudding user response:

Maybe you want something like this using group = mortality:

df <- read.table(text = "MCV   mortality
 100   0
 100   1
  90   1
  70   1
  70   0", header = TRUE)

library(ggplot2)
ggplot(data=df, aes(MCV, fill=factor(mortality), group = mortality))   
  geom_histogram(aes(y=c(..count..[..group..==1]/sum(..count..))),
                 position='dodge', binwidth=5)  
  ylab("Percentage")   
  xlab("MCV")

Created on 2022-08-31 with reprex v2.0.2

  • Related