I am trying to make a (1 row, 3 column) array of barplots that all have the same bar width.
All three bar plots have a different number of observations and hence the width of the bars end up different for each plot (i.e. plot with the most observations has the narrowest bars and the plot with the fewest observations has the widest bars). I understand from the barplot {graphics} R documentation that,
“Specifying a single value will have no visible effect unless
xlimis specified”
However, my x labels are strings, so I’m not sure how to specify xlim. I don’t mind if my plots are different widths, but do I need to specify this somehow?
Here is some fake data and the code I am using… thank you for your help.
height4plot1 <- c(1,6,9,2,3,10,7,15)
names4plot1 <- c("P1","P2","P3","P4","P5","P6","P7","P8")
height4plot2 <- c(5,4,10,2)
names4plot2 <- c("M1","M2","M3","M4")
height4plot3 <- c(4,12)
names4plot3 <0 c("U1","U2")
par(mfrow=c(1,3),
mar=c(10,5,2,1),
cex.axis=0.7,
mgp=c(3,0.5,0))
barplot(height4plot1,
names.arg=names4plot1,
las=3,
axes=TRUE,
axisnames=TRUE,
ylab="YLAB",
ylim=ylim,
plot=TRUE,
main="PLOT1",
width=1)
barplot(height4plot2,
names.arg=names4plot2,
las=3,
axes=TRUE,
axisnames=TRUE,
ylim=ylim,
plot=TRUE,
main="PLOT2",
width=1)
barplot(height4plot3,
names.arg=names4plot3,
las=3,
axes=TRUE,
axisnames=TRUE,
ylim=ylim,
plot=TRUE,
main="PLOT3",
width=1)
Without the variables like
height4plot1etc. it is harder to test your code and modifications, but here are some possibilities:You can specify
width=0.8for each plot andxlim=c(0,maxnum)where maxnum is the maximum numbers of bars in the different plots. This will leave an empty section in each of the smaller bar plots.You could pad the shorter vectors of heights with
NAuntil they are all the same length (this would still give the empty sections).You could concatenate your 3 vectors together and make a single boxplot, possibly coloring the 3 groups differently to help distinquish them. The
ablinefunction can be used to add divider lines between the groups (and see thespaceargument to barplot, or include an ‘NA’ as divider to give more space between the groups). You can use the return value to help in placing titles above each group.You can use
layoutinstead ofparto set up your 3 plotting areas to have different widths, but getting the exact ratios of widths to give the exact same size bars will not be simple (you may get close with trial and error though). If you really want this route thengrconvertXandoptimmay help.I would suggest the 2nd option above.