5

I'm using ggplot2 to create a stacked area chart showing footprint (area) of a number of different research stations over time. I would like something that looks like the chart below, but with Area on the y axis and colored by the different research stations:

stacked area chart
(source: r-graph-gallery.com)

I've tried elements of similar posts, but can't get it to work.

Trouble with ggplot in R - "Error in f(...) : Aesthetics can not vary with a ribbon"

Getting a stacked area plot in R

https://www.r-graph-gallery.com/136-stacked-area-chart/

I've provided a .csv subset of the data here.

Below is the code that I'm using.

fp <- read.csv("fp.csv")

fp$Year <- as.numeric(rep(fp$Year)) #change Year to numeric

p2 <- fp %>% 
  filter(Exist == 1) %>% # Select only existing structures
  group_by(Year, Station) %>%
  summarise(Sum_Area = sum(Area)) %>% 
  arrange(desc(Year)) %>% 
  ggplot(aes(x = Year, y = Sum_Area, fill = Sum_Area)) +
  geom_area(stat = "identity", position = "stack")
p2

I always get the error message: Error in f(...) : Aesthetics can not vary with a ribbon

Community
  • 1
  • 1
cms
  • 83
  • 1
  • 2
  • 4
  • I think the only mistake you have is that you should replace `fill = Sum_Area` with `fill = Station` since you want the colors to be the different research stations. Also FYI in the sample data you provide, the areas for each station are the same for every year so there is no variation among years as in the example picture from r-graph-gallery. – qdread Aug 02 '19 at 21:02
  • Well I feel a bit silly. Thanks for that qdread. Thanks for the heads up about the sample data--there is some variation later on. – cms Aug 02 '19 at 21:33
  • My output is very choppy...is there an easy way to fix this? https://www.dropbox.com/s/b4uen91hc36qghj/area_chart.png?dl=0 – cms Aug 02 '19 at 21:36
  • Hard to tell without being able to look at all the data – qdread Aug 03 '19 at 03:12

1 Answers1

6

This can happen if your fill variable is an integer or numeric variable instead of a character or factor variable.

Reproduce the error

airquality %>%
    ggplot(aes(x = Day, y = Ozone, fill = Month)) +
    geom_area()
#Error: Aesthetics can not vary with a ribbon

Fix the error

airquality %>%
    mutate(Month = as.character(Month)) %>%
    ggplot(aes(x = Day, y = Ozone, fill = Month)) +
    geom_area()

This is certainly a useless plot, just to illustrate the error.

Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110