stacked plot in R

[This article was first published on Ensemble Blogging, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Consider the following example: there is a three-stage truck maintenance pipeline. Initially, when a Truck comes to the maintenance service, it is added to the first stage and its status in the pipeline is set to “New”. When the technicians start working on it, for diagnosis the problem and removing the issue, its status is changed to “in progress”. When the truck is released from maintenance service its status is change to “released”. Note that a track status can convert from “New” to “released”, if the technicians believe there is nothing wrong with the system and it was just a false alarm.

The pipeline manager would like to know that for a set of trucks coming for maintenance how their statuses change over time. This is called for a stacked plot where the number of trucks in different stages are plotted in stack format. Stack plots are fairly easy to create in R and here is how:

Suppose we have the following data frame:


In this data frame, level is the status of the maintenance, date is the date of status update, and data is the number of trucks in that date with that status.

In order to plot the data in stacked format, we use geom_area in ggplot2 and set the position field to stacked. 

p <- ggplot(maintanance_df, aes( day, data))
p + geom_area(aes(colour = level, fill= level), position = 'stack') +
  scale_x_discrete(labels = xlabel) + 
  xlab("date") +
  ylab("# of trucks") +
  ggtitle("Status of trucks in maintenance pipeline")
This would result in the following stacked plot:

To leave a comment for the author, please follow the link and comment on their blog: Ensemble Blogging.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)