Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this histogram in ggplot / R?

Please find My data q below.

I have two covariates: q$Studie and q$best.resp corresponding to five different studies each reporting the best response obtained after a certain treatment.

q$best.resp has three levels

table(q$best.resp)

 0  1  2 
62 42  2  

I want to produce a histogram that illustrate each q$best.resp per all q$Studie and all studies combined (corresponding to the table(q$best.resp))

I have drawn this example of how I would like the plot to look like. Unfortunately, I have not succeeded through manuals.

enter image description here

I would prefer a solution in ggplot2. Please note that all studies only have q$best.resp==0 or q$best.resp==1 - except for q$Studie==5, that solitarily have two cases of q$best.resp==2

My data 
q <- structure(list(Studie = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 
5L), best.resp = c(0L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 
1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 
0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 
1L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 2L, 0L, 2L)), .Names = c("Studie", 
"best.resp"), class = "data.frame", row.names = c(NA, -106L))
like image 597
cmirian Avatar asked Jun 18 '19 09:06

cmirian


1 Answers

You can try a tidyverse

library(tidyverse)
q %>% 
  as_tibble() %>% 
  mutate(Studie=as.character(Studie),
         best.resp =as.factor(best.resp)) %>% 
  bind_rows(., mutate(., Studie="all")) %>% 
  count(Studie, best.resp) %>% 
  ggplot(aes(Studie, n, fill= best.resp)) + 
   geom_col(position = position_dodge2(preserve = "single"))

enter image description here

like image 143
Roman Avatar answered Nov 15 '22 05:11

Roman