Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_area overlay area plots in front of each other

Tags:

r

ggplot2

I am trying to make an area plot with the different areas are overlaid on one another rather than stacked.

I have a dataframe that looks like this:

     r   variable      value
1  45.0    Cat 1   4.057250e+03
2  52.5    Cat 1   3.537323e+03
3  56.1    Cat 1   3.429861e+03
4  57.3    Cat 1   3.395330e+03
5  57.6    Cat 1   3.389983e+03
6  45.0    Cat 2   4.545455e-03
7  52.5    Cat 2   4.509400e+01
8  56.1    Cat 2   3.525753e+02
9  57.3    Cat 2   4.185094e+02
10 57.6    Cat 2   4.336622e+02
11 45.0    Cat 3   4.074432e+03
12 52.5    Cat 3   3.630504e+03
13 56.1    Cat 3   3.919076e+03
14 57.3    Cat 3   3.957039e+03
15 57.6    Cat 3   3.970083e+03
16 45.0    Cat 4   1.718182e+01
17 52.5    Cat 4   9.318133e+01
18 56.1    Cat 4   4.892154e+02
19 57.3    Cat 4   5.617087e+02
20 57.6    Cat 4   5.801001e+02

I am trying to get area plots for each category. My code for that is:

p <- ggplot(reshaped_data, aes(r, value))
p <- p + labs(x = "X Axis", y = "Y Axis") + ggtitle(title)  
p <- p + geom_area(aes(colour = variable, fill= variable), position = 'stack')   
p

And the result I am getting looks like this: Generated Graph

How can I make it so that the area graphs aren't stacked on each other, but the smallest are overlaid in front of the bigger ones?

Thanks

like image 336
home_wrecker Avatar asked Nov 09 '16 20:11

home_wrecker


2 Answers

Using tidyverse:

library(forcats)
p + geom_area(aes(colour = variable, 
fill= fct_reorder(variable, value, .desc = TRUE)), position = 'identity') 

Remove .desc = TRUE if it does the opposite of what you want.

like image 175
Phil Avatar answered Sep 24 '22 00:09

Phil


As Nathan wrote you have to use geom_area(position = "identity", ...)

But before this you should reorder the levels of variable:

df$variable <- factor(df$variable, unique(df[order(df$value, decreasing = T),"variable"]) )

or

df$variable <- reorder(df$variable, df$value, function(x) -max(x) )
like image 39
HubertL Avatar answered Sep 25 '22 00:09

HubertL