Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouped and stacked barplot using base R

Tags:

graph

r

bar-chart

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:

enter image description here

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.

like image 577
jon Avatar asked Oct 07 '15 16:10

jon


People also ask

How do you make a stacked barplot in R?

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.

How do I make a grouped bar chart in R?

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.


2 Answers

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)

enter image description here

like image 134
Cath Avatar answered Oct 21 '22 01:10

Cath


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")

enter image description here

like image 4
jeremycg Avatar answered Oct 21 '22 01:10

jeremycg