为什么我的barplot不能在R / ggplot2中工作?

时间:2018-01-18 12:00:51

标签: r ggplot2 graph

我在ggplot2中制作条形图时遇到了困难。我已经关注了instructions但我在编程方面还不太确定。

library(ggplot2)

## Load my data
d <- structure(list(author = structure(c(1L, 2L, 4L, 3L, 5L, 6L), .Label = c("Bahr et al", "Fuller et al", "Garbossa et al", "Gokhale et al", "Iuchi et al", "Lee et al"), class = "factor"), nAE = c(22L, 34L, 158L, 90L, 70L, 41L), AE = c(3L, 1L, 7L, 1L, 3L, 10L), SAE = c(0L, 1L, 0L, 0L, 0L, 0L)), .Names = c("author", "nAE", "AE", "SAE"), class = "data.frame", row.names = c(NA, -6L))

## This is as far as I get
ggplot(data=d, aes(x=nAE, y=author, fill=AE))

我希望我的情节看起来像这样: enter image description here

我的数据包含

head(d)
          author nAE AE SAE
1     Bahr et al  22  3   0
2   Fuller et al  34  1   1
3  Gokhale et al 158  7   0
4 Garbossa et al  90  1   0
5    Iuchi et al  70  3   0
6      Lee et al  41 10   0

这是关于药物A副作用的六项研究.d $ nAE是没有副作用的人数,d $ AE代表有不良反应的患者,而d $ sAE代表有严重副作用的患者。

我希望我的情节能够在每项研究中说明这三个值。为了与附加的ggplot进行比较,红色可以看到d $ nAE,绿色d $ AE和蓝色d $ sAE。

提前致谢, 下进行。

1 个答案:

答案 0 :(得分:2)

我们可以使用dplyrtidyrggplot2执行以下操作:

library(dplyr)
library(tidyr)
library(ggplot2)

d <- structure(list(author = structure(c(1L, 2L, 4L, 3L, 5L, 6L), .Label = c("Bahr et al", "Fuller et al", "Garbossa et al", "Gokhale et al", "Iuchi et al", "Lee et al"), class = "factor"), nAE = c(22L, 34L, 158L, 90L, 70L, 41L), AE = c(3L, 1L, 7L, 1L, 3L, 10L), SAE = c(0L, 1L, 0L, 0L, 0L, 0L)), .Names = c("author", "nAE", "AE", "SAE"), class = "data.frame", row.names = c(NA, -6L))

categories <- c("Adverse Effect", "No adverse effects", "Severe side effects")
cols <- c("#E61515", "#105415", "#5121E0")

d %>% 
  gather(key, value, -author) %>% 
  ggplot(aes(author, value, fill = key)) +
  geom_col() + 
  coord_flip() +
  theme_bw() +
  theme(legend.position = "top") +
  scale_fill_manual(labels = categories, values = cols) +
  labs(fill = "Authors")

enter image description here

要选择自己的颜色,RStudio有一个方便的插件,名为拾色器,您可能想要查看。