R bar chart colours for groups of bars

妖精的绣舞 提交于 2019-12-16 18:07:50

问题


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

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

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?


回答1:


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

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().

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

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



来源:https://stackoverflow.com/questions/15087902/r-bar-chart-colours-for-groups-of-bars

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!