如何在R中一次生成多个条形图?

时间:2017-11-23 12:37:19

标签: r ggplot2 charts bar-chart

我有超过100个原始的excel表。对于具有X和Y轴标签的所有原始数据,如何为每个原始数据单独生成条形图?

  • 首先没有标准错误

  • 接下来出现标准错误

此处示例显示3个原始数据。 期待您的支持。

Status  Sample 1    Sample 2    Sample 3    Sample 4    Sample 5    Sample 6    Sample 7    Sample 8    Sample 9    Sample 10
AA1 1.457958966 1.082728155 1.421862008 1.282919309 1.365338194 1.825823721 1.442458653 1.301820193 0.605102201 0.795770198
AB2 0.215245986 0.232381653 0.206548478 0.203164578 0.476502255 0.178929005 0.2419442   0.381018497 1.00597396  0.722438532
AZ1 0.297877541 0.313489112 0.251719576 0.272301642 0.354067746 0.326371147 0.268637474 0.344993509 1.912717065 1.22454492

enter image description here

1 个答案:

答案 0 :(得分:2)

我想你已经知道如何将你的数据从excel变成R.我已经创建了一个示例数据帧:

df <- data.frame(
  sample1 = runif(4, 0, 2),
  sample2 = runif(4, 0, 2),
  sample3 = runif(4, 0, 2),
  sample4 = runif(4, 0, 2),
  sample5 = runif(4, 0, 2),
  status = c("AA1", "AB2", "AZ1", "AX4")
)

> df
    sample1    sample2   sample3    sample4   sample5 status
1 0.8932929 1.31205570 1.9886886 0.05468494 0.8996559    AA1
2 0.9979367 0.02584171 0.6417443 0.53378421 0.9303479    AB2
3 1.8358270 1.49354287 0.2439607 1.72527919 0.7083448    AZ1
4 1.2310165 1.93928257 1.2704148 0.22660472 1.6099852    AX4

现在我们需要使用melt

中的reshape2函数重新格式化此数据框
library(reshape2)
df_melted <- melt(df, value.name = "value")

> df_melted
   status variable      value
1     AA1  sample1 0.89329292
2     AB2  sample1 0.99793671
3     AZ1  sample1 1.83582702
4     AX4  sample1 1.23101645
5     AA1  sample2 1.31205570
6     AB2  sample2 0.02584171
7     AZ1  sample2 1.49354287
8     AX4  sample2 1.93928257
            ...

现在我们可以使用ggplot绘制数据,并使用facet_wrap我们为每个状态分别绘制

library(ggplot2)
ggplot(data = df_melted, aes(x = variable, y = value)) + geom_col() + facet_wrap(~status)

enter image description here