There are multiple solutions to create a stacked bar plot in R, but how to draw a stacked line plot?
Stacked Line charts show the contribution to trends in the data. This is done by stacking lines on top of each other. Stacked Line charts are used with data which can be placed in an order, from low to high. The charts are used when you have more than one data column which all add up to the total trend.
A stacked line plot can be created with the ggplot2
package.
Some example data:
set.seed(11)
df <- data.frame(a = rlnorm(30), b = 1:10, c = rep(LETTERS[1:3], each = 10))
The function for this kind of plot is geom_area
:
library(ggplot2)
ggplot(df, aes(x = b, y = a, fill = c)) + geom_area(position = 'stack')
Given that the diagram data is available as data frame with "lines" in columns and the Y-values in rows and given that the row.names are the X-values, this script creates stacked line charts using the polygon function.
stackplot = function(data, ylim=NA, main=NA, colors=NA, xlab=NA, ylab=NA) {
# stacked line plot
if (is.na(ylim)) {
ylim=c(0, max(rowSums(data, na.rm=T)))
}
if (is.na(colors)) {
colors = c("green","red","lightgray","blue","orange","purple", "yellow")
}
xval = as.numeric(row.names(data))
summary = rep(0, nrow(data))
recent = summary
# Create empty plot
plot(c(-100), c(-100), xlim=c(min(xval, na.rm=T), max(xval, na.rm=T)), ylim=ylim, main=main, xlab=xlab, ylab=ylab)
# One polygon per column
cols = names(data)
for (c in 1:length(cols)) {
current = data[[cols[[c]]]]
summary = summary + current
polygon(
x=c(xval, rev(xval)),
y=c(summary, rev(recent)),
col=colors[[c]]
)
recent = summary
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With