cms
cms

Reputation: 83

How to fix Error in f(...) : Aesthetics can not vary with a ribbon

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

Upvotes: 5

Views: 12449

Answers (1)

Paul Rougieux
Paul Rougieux

Reputation: 11429

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.

Upvotes: 6

Related Questions