我想创建一个组合条形图,其中data1和data2被堆叠,而data1和data2被分组在基础R图形中.
这样的安排:
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)
Run Code Online (Sandbox Code Playgroud)
知道我该怎么办?我知道我们可以使用不同的图或刻面来做到这一点,但我想在一个图中并排显示它们.
您可以使用参数space来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)
Run Code Online (Sandbox Code Playgroud)