Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 factor x variable breaks geom_area

Tags:

r

ggplot2

I've been trying to produce a stacked area chart with a discrete x variable (because I want to display financial year, i.e. "2013/14", rather than calendar year). However, turning the x-axis variable into a factor prevents the geom from being rendered in the final chart.

Is there a way around this?

library(ggplot2)

dat <- structure(list(year = c(13, 13, 14, 14, 15, 15), 
                      group_lvl = structure(c(1L, 2L, 1L, 2L, 1L, 2L), 
                                            .Label = c("a", "b"), class = "factor"), 
                      val = c(35, 65, 50, 50, 75, 25)), 
                 .Names = c("year", "group_lvl", "val"), row.names = c(NA, -6L), 
                 class = "data.frame")
dat
  year group_lvl val
1   13         a  35
2   13         b  65
3   14         a  50
4   14         b  50
5   15         a  75
6   15         b  25

ggplot(dat, aes(x = year, y = val)) + 
  geom_area(aes(fill = group_lvl), position = "stack")

enter image description here

dat$year <- factor(dat$year)

ggplot(dat, aes(x = year, y = val)) + 
  geom_area(aes(fill = group_lvl), position = "stack")

enter image description here

sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_2.1.0

loaded via a namespace (and not attached):
 [1] labeling_0.3     colorspace_1.2-6 scales_0.4.0     plyr_1.8.3       tools_3.3.0     
 [6] gtable_0.2.0     Rcpp_0.12.4      grid_3.3.0       digest_0.6.9     munsell_0.4.3   
like image 831
r.bot Avatar asked Jun 07 '26 01:06

r.bot


1 Answers

Just add breaks, no need to make it a factor.

ggplot(dat, aes(x = year, y = val)) + 
  geom_area(aes(fill = group_lvl), position = "stack") + 
  scale_x_continuous(breaks=c(13,14,15),labels=c("2013","2014","2015"))

enter image description here

like image 54
Adam Birenbaum Avatar answered Jun 09 '26 12:06

Adam Birenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!