如何在ggplot / R中制作此直方图?

时间:2019-06-18 09:19:00

标签: r ggplot2 histogram

请在下面找到My data q

我有两个协变量:q$Studieq$best.resp对应于五项不同的研究,每项研究都报告了经过某种治疗后获得的最佳反应。

q$best.resp具有三个级别

table(q$best.resp)

 0  1  2 
62 42  2  

我想生成一个直方图,以说明所有q$best.resp和所有组合研究的每个q$Studie(对应于table(q$best.resp)

我已经绘制了一个示例,说明如何绘制该图。不幸的是,我没有通过手册获得成功。

enter image description here

我更喜欢ggplot2中的解决方案。请注意,所有研究仅包含q$best.resp==0q$best.resp==1-q$Studie==5除外,单独有两个案例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))

1 个答案:

答案 0 :(得分:3)

您可以尝试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

相关问题