-1

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?

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
DinoDave
  • 33
  • 1
  • 3
  • There are many many posts covering this topic: see [**here**](http://stackoverflow.com/questions/15071334/boxplot-of-table-using-ggplot2/15071393#15071393), [**here**](http://stackoverflow.com/questions/10352894/barplot-using-ggplot2) for example. If this doesn't solve, do a search on SO for barplot with tag `[r]`. – Arun Feb 26 '13 at 11:29
  • @agstudy, :) oh crap! I'll replace it now. give me a minute – Arun Feb 26 '13 at 11:55
  • Check [**this**](http://stackoverflow.com/questions/12383489/colour-of-geom-bar), [**this**](http://stackoverflow.com/questions/10352894/barplot-using-ggplot2) instead. Sorry for the wrong links. – Arun Feb 26 '13 at 11:57
  • 2
    You should seriously reconsider producing a bar plot with 100 bars. I am confident that there are better options to present your data. – Roland Feb 26 '13 at 12:00
  • (+1) @Roland. To add to it, And it wouldn't be possible to choose colors in the "discrete" manner as Didzis (nice answer btw) has shown below. You'll have to use probably a gradient. And yes, its a lot of bars.. – Arun Feb 26 '13 at 12:03

1 Answers1

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

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201