user9695427
user9695427

Reputation:

How to generate multiple bar graphs at once in R?

I 've an excel sheet with more than 100 raws. How can I generate bar graph for each raw separately at once for all the raws with X and Y axis labels?

Here example shows for 3 raws. Expecting your kind support.

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

Upvotes: 0

Views: 1493

Answers (1)

f.lechleitner
f.lechleitner

Reputation: 3812

I guess you already know how to get your data from excel into R. I've created a sample dataframe:

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

Now we need to reformat this dataframe using the melt function from 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
            ...

So now we can plot the data with ggplot, and using facet_wrap we get seperate plots for every status

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

enter image description here

Upvotes: 2

Related Questions