Question

Very stupid question but I can't find the answer online:

Need to plot multiple barplots together like this:

 i=1:4
 main = paste ("Location ", i)

 windows()
 par(mfrow=c(2,2))
 a<-table(c(rep(10, 6), rep(4, 32)))
 b<-table(c(rep(9, 6), rep(10, 32), rep(11,4)))
 c<-table(c(rep(10, 6)))
 d<-table(c(rep(10, 3), rep(9, 3), rep(8, 5)))

 barplot(a,  main=main[1], xlab='RSSI')
 barplot(b,  main=main[2], xlab='RSSI')
 barplot(c,  main=main[3], xlab='RSSI')#, width=0.5
 barplot(d,  main=main[4], xlab='RSSI')

1) is it possible to maintain constant the axes scale, so that it is the same on every graph?

2) is it possible to maintain constant the bar width in the graphs? I tried with width but it does not seem to work and i would like to have it constant and fixed between graphs.

Thanks

EDIT: for 2) I know you can add zeros, so that all the graphics have the same number of classes involved, but since I am plotting in a for loop that I have removed to make the example simpler, I would rather use another way to do it, if it is possible. Thanks again

Was it helpful?

Solution 2

Have a look at the xlim and ylim argument described in ?barplot:

barplot(a,  main=main[1], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))
barplot(b,  main=main[2], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))
barplot(c,  main=main[3], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))
barplot(d,  main=main[4], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))

enter image description here

(xlim and width influence each other.)

OTHER TIPS

Possibly it was only for your example that you kept the data for each plot in separate vectors. Anyway, if the number of locations would be much bigger, you will soon have your workspace cluttered with small vectors, and you would have to call tableand barplot many times.

It would be much easier to work with the data stored in a data frame, regardless if you plot using base R functions, or ggplot. Furthermore, it might be easier to compare counts for different levels of RSSI, among the different locations, if the same set of classes for each location is used in each plot, i.e. that also RSSI classes with zero counts were included. You might also use the same scale of the y axis across locations. Here is a small example with ggplot

library(ggplot2)

# create a data frame with the data in your vectors
# 'x' is the value, and 'loc' the location of each registration
df <- data.frame(x = c(rep(10, 6), rep(4, 32),
                       rep(9, 6), rep(10, 32), rep(11, 4),
                       rep(10, 6),
                       rep(10, 3), rep(9, 3), rep(8, 5)),
                 loc = c(rep("a", 6+32), rep("b", 6+32+4), rep("c", 6), rep("d", 3+3+5)))

# plot using geom_bar, which default counts the cases for each level of  - no need for 'table'
ggplot(data = df, aes(x = factor(x))) +
  geom_bar() +
  facet_wrap(~ loc)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top