I would like to create a combination bar plot where within data1 and data2 are stacked while between data1 and data2 are grouped in base R graphics.
Something like this in arrangement:
data1 <- matrix(c(1:5, rep(1,5), rep(4,5)), ncol=5)
data2 <- matrix(c(2:6, rep(2,5), rep(3,5)), ncol=5)
# stacked bar
barplot(data1)
#grouped var
barplot(data1, beside=TRUE)
Any idea how can I do this? I know we can do this using different plots or facets but I would like to present them side by side in a single plot.
In order to create a stacked bar chart, also known as stacked bar graph or stacked bar plot, you can use barplot from base R graphics. Note that you can add a title, a subtitle, the axes labels with the corresponding arguments or remove the axes setting axes = FALSE , among other customization arguments.
Method 2: Creating A Grouped Barplot Using ggplot2 Package Then the user needs to call the geom_bar() function from the ggplot package with the required parameters into it to create the grouped bar plot in the R programming language.
You can use the argument space
of barplot
to shift the second barplot:
# plot first barplot, using xlim to ensure there is enough space to plot the second one
# (here the spaces are all 0, so the bars are grouped together)
barplot(data1, space=0, xlim=c(-1, ncol(data1)+ncol(data2)+1), las=1)
# plot second barplot (with add=TRUE so the bars appear on the same plot),
# putting a space of 6 (the number of columns of data1 + 1) at the beginning,
# to plot the "new" bars on the right of the first bars (the other spaces are 0):
barplot(data2, space=c(ncol(data1)+1, rep(0, ncol(data2)-1)), las=1, add=TRUE)
You can try using mfrow
to plot two plots side by side:
par(mfrow = c(1,2))
barplot(data1, ylim = c(0,13), xlab = "data1")
barplot(data2, ylim = c(0,13), axes = FALSE, xlab = "data2")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With