使用基数R分组和堆叠的条形图 [英] Grouped and stacked barplot using base R

查看:54
本文介绍了使用基数R分组和堆叠的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个组合条形图,其中在data1和data2内堆叠,而在data1和data2之间以基础R图形分组.

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.

这样的安排:

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.

推荐答案

您可以使用 barplot 的参数 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)

这篇关于使用基数R分组和堆叠的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆