条形组的 R 条形图颜色 [英] R bar chart colours for groups of bars

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

问题描述

R 的新手很抱歉,如果这是一个愚蠢的问题.

Fairly new to R so sorry if this is a dumb question.

我想绘制一个包含大量数据的条形图 - 可能是 100 个条形图.

I want to plot a bar chart of a lot of data - maybe 100 bars.

我想使用颜色和间距来突出显示组",所以我可能有前 10 个蓝色条,一个小间隙,接下来的 20 个红色,一个小间隙等等.

I want to use colours and spacing to highlight the "groups", so I might have the first 10 bars in blue, a small gap, the next 20 in red, a small gap and so on.

我可以很好地绘制数据,但是如何以这种方式进行着色和间隙?

I can plot the data fine, but how can I do the colouring and gaps in this way?

推荐答案

这可以通过@Arun 链接中提供的 ggplot2 轻松完成.

This can be done quite easily with ggplot2 as provided in links by @Arun.

使用基本图形来设置条之间的空间,您可以使用参数 space=(在每个条之前设置空间)和参数 col= 将改变函数 中的颜色barplot().

With base graphics to set space between bars you can use argument space= (sets space before each bar) and argument col= will change color in function barplot().

这是一个示例,其中有 20 个条形,每 5 个条形之间有空格.

Here is a example with 20 bars and space between each 5 bars.

df<-sample(1:10,20,replace=T)
barplot(df,space=c(0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0),
        col=rep(c("red","blue","green","yellow"),each=5))

如果每组中的观察数相同,那么您可以将值向量转换为矩阵,然后绘制它(参数 beside=TRUE).在这种情况下,您只需要提供颜色,条形就会自动分组.

If the number of observations in each group is identical then you can convert vector of values to matrix and then plot it (with argument beside=TRUE). In this case you just need to supply colors but bars will be grouped automatically.

df2<-matrix(df,ncol=4)
barplot(df2,beside=TRUE,col=rep(c("red","blue","green","yellow"),each=5))

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

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