I have the following data frame and want to plot a stacked area plot:
library(ggplot2)
set.seed(11)
df <- data.frame(a = rlnorm(30), b = as.factor(1:10), c = rep(LETTERS[1:3], each = 10))
ggplot(df, aes(x = as.numeric(b), y = a, fill = c)) +
geom_area(position = 'stack') +
theme_grey() +
scale_x_discrete(labels = levels(as.factor(df$b))) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
The resulting plot on my system looks like this:
Unfortunately, the x-axis doesn't seem to show up. I want to plot the values of df$b
rotated so that they don't overlap, and ultimately I would like to sort them in a specific way (haven't gotten that far yet, but I will take any suggestions).
Also, according to ?factor()
using as.numeric()
with a factor is not the best way to do it. When I call ggplot
but leave out the as.numeric()
for aes(x=...
the plot comes up empty.
Is there a better way to do this?
Leave b
as a factor. You will further need to add a group
aesthetic which is the same as the fill
aesthetic. (This tells ggplot
how to "connect the dots" between separate factor levels.)
ggplot(df, aes(x = b, y = a, fill = c, group = c)) +
geom_area(position = 'stack') +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
As for the order, the x-axis will go in the order of the factor levels. To change the order of the axis simply change the order of the factor levels. reorder()
works well if you are basing it on a numeric column (or a function of a numeric column). For arbitrary orders, just specify the order of the levels directly in a factor
call, something like: df$b = factor(df$b, levels = c("1", "5", "2", ...)
For more examples of this, see the r-faq Order bars in ggplot. Yours isn't a barplot but the principle is identical.