问题
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