-1

I'm trying to create a stacked bar chart from data held in a data frame that has two columns. An example of the data format is below:

Date    Speed  
01/01/2013  56  
01/01/2013  45  
01/01/2013  34  
02/01/2013  23  
02/01/2013  12  
02/01/2013  1  
03/01/2013  48 

For each day I need to count the number of entries that fall into each category (defined by limits e.g., 0-40, 41-48, 49-60, > 60) and then plot the counts for each day as a stacked bar chart.

I can do this by counting the number of entries for each day separately, and putting the results into a new data frame of the right format to plot using the standard stacked bar chart command. But this is an inefficient approach. I haven't been able to find a more elegant method in my searches but I believe one must exist.

I would like to use only the standard packages to do this as I cannot install new packages on the system I have available to me.

Sam Firke
  • 21,571
  • 9
  • 87
  • 105
Pete
  • 21
  • 4

1 Answers1

1

You can use a base barplot here. Here an example

dd<-read.table(text="Date Speed
01/01/2013 56
01/01/2013 45
01/01/2013 34
02/01/2013 23
02/01/2013 12
02/01/2013 1
03/01/2013 48", header=T)

#make sure it's a date    
speed_date <- as.Date(dd$Date, "%m/%d/%Y")

#cut data into requested bins
speed_cut <- cut(dd$Speed, 
    breaks=c(0,40,48,60,Inf),
    labels=c("0-40", "41-48", "49-60", "> 60")
)

#pick a color for each bin
speed_cols <- heat.colors(nlevels(speed_cut))

barplot(table(speed_cut, speed_date), col=speed_cols)
legend("topright",levels(speed_cut), fill=speed_cols)

this produces

enter image description here

You may wish to change the colors to suit your taste.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Perfect. Many thanks. R continues to amaze me with how easy it makes these sorts of task...once you know how to do them of course! – Pete Jan 26 '15 at 20:16