# the data frame SpecGroup.rda should be loaded # example how to create a stacked bar-plot by grouping the data from the SpecGroup.rda file # first address the capitals, by making them all the same: SpecGroup$Speciality <- ifelse(SpecGroup$Speciality=="oncology", "Oncology",SpecGroup$Speciality) SpecGroup$Speciality <- ifelse(SpecGroup$Speciality=="Ortho", "Orthopaedics",SpecGroup$Speciality) SpecGroup$Speciality <- ifelse(SpecGroup$Speciality=="ortho", "Orthopaedics",SpecGroup$Speciality) # this dataframe now has duplicate values (which complicate the plot)!! # to add the duplicates grouped by Month, Group and Speciality adding the variable Number; use the ddply function in the plyr package: # call the new dataframe SpecGroup1 library(plyr) SpecGroup1<-ddply(SpecGroup,c("Month","Group","Speciality"),numcolwise(sum)) # add as defined similar to the unique function # for the data labels (numbers on top of the bars) to be postioned correctly it is necessary to calculate the cumsum # use the ddply in the plyr package function for this: # calculate the cumsum in a new dataframe called SpecGroup2 SpecGroup2<-ddply(SpecGroup1, c("Speciality","Month"),transform,ypos=cumsum(Number)) # Rather than having the month and year, create month names for the plot: # Again use the plyr package for this and save it as a new variable in the same dataframe (but without a capital letter): SpecGroup2$month<-mapvalues(SpecGroup2$Month,from=c('01/2016','02/2016','03/2016','04/2016','05/2016','06/2016','07/2016','08/2016','09/2016','10/2016','11/2016','12/2016'),to=c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')) # now create a stacke bar plot with facets dev.new() # new plot window ggplot(SpecGroup2, aes(x=month, y= Number,fill=Group)) + # a bar plot using the SpecGroup2 dataframe with variables month and Number and the Group as fill geom_bar(stat='identity',position='stack')+ # define a stacked bar plot facet_grid(~Speciality)+ # define a facet to group the data further theme_bw(base_size=12)+ # remove grey scales and set the font size geom_text(aes(y=ypos,label=Number),vjust=1.0, color="white", size=3.5) + # make sure tha labels are correctly positined as defined above with the ypos variable ggtitle(label = 'MDT Activity 2016') + # give the plot a title xlab(label = 'Month') + # x axis label ylab(label = 'Number')+ # y axis label scale_x_discrete(limits = c('Jan','Feb','Mar','Apr','May','Jun')) # define the scale so that only these months show