0
votes

For a report I am summarizing data by a group. Due to copyright issues I have created some dummy data below (first colum is group, then values):

  X   A   B  C D
1   1  12   0 12 0
2   2  24   0 15 0
3   3  56   0 48 0
4   4  89   0 96 0
5   5  13   3 65 0
6   6  11  16  0 0
7   7  25  19  0 0
8   8  24  98  0 0
9   9  18 111  0 0
10 10 173 125  0 0
11 11  10  65  0 0

I would like to create a barplot for every group (1:11) with a loop:

for(i in 1:11){x<-dummyloop[i,]
  barplot(as.matrix(x), main=paste("Group", i), ylim=c(0,200))}

This works, I get a barplot for every loop, however they end up in one 4 by for plotting window as if I had used par(mfrow=c(4,4)). I need individual bar plots.

So I used par(mfrow=c(1,1)), which for some reason fixed the problem (I don't use par EVER, because I am only exporting for a scientific report featuring individual graphs), however the "main" is cut off on the top.

I would also like each bar to be a different color, so I used:

 for(i in 1:11){x<-dummyloop[i,]
      barplot(as.matrix(x), main=paste("Group", i), col=c(1:5), 
ylim=c(0,200))}

Realizing that the coloring vector then only uses the first color, I tried variations of this:

for(i in 1:11){x<-dummyloop[i,]
  barplot(as.matrix(x), main=paste("Group", i), col=c(4:10)[1:ncol(x)], 
ylim=c(0,200))}

which doesn't do the trick...

I seem to be missing some key detail in the for loop here, thanks for help. I'm an R novice getting better every day thanks to the people here ;).

2
you might want to change the title of your question since thats not your problem any longer.Humpelstielzchen

2 Answers

1
votes

No idea, why that is in base plot. Here is a alternative way with ggplot2.


for(i in 1:11){x<- gather(data[i,])
print(ggplot(data = x, aes(x = key, y = value, fill = cols)) +
  geom_bar(stat = "identity", show.legend = FALSE) + 
    ggtitle(paste("Group ", i)) + theme(plot.title = element_text(hjust = 0.5)) +
    ylim(0,200))  
  }

So is your mainstill cut off?

Then extend the margin on top of the plot. Execute:


par(mar = c(2, 2, 3 , 2)) # c(bottom, left, top, right)

Before plotting. You can reset your specifications with dev.off() when experimenting.

0
votes

Staying base R, you simply could use by and set col according to the group.

colors <- rainbow(length(unique(dat$X)))  # define colors, 11 in your case

by(dat, dat$X, function(x) 
  barplot(as.matrix(x), main=paste("Group", x$X), ylim=c(0, 200), col=colors[x$X]))

Data

dat <- structure(list(X = 1:11, A = c(12L, 24L, 56L, 89L, 13L, 11L, 
25L, 24L, 18L, 173L, 10L), B = c(0L, 0L, 0L, 0L, 3L, 16L, 19L, 
98L, 111L, 125L, 65L), C = c(12L, 15L, 48L, 96L, 65L, 0L, 0L, 
0L, 0L, 0L, 0L), D = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10", "11"))