ggplot: geom_area - error with aes(Fill)

Asked

Viewed 47 times

3

I have the following data and would like to create a chart with the ggplot2::geom_area() with different colors for the positive and negative values. However, I am getting an error and I am not being able to solve it. Could someone help?

dados <- structure(list(year = c(2020, 2020, 2020, 2020, 2020, 2020, 2020, 
2020, 2020, 2020, 2020, 2020), month = structure(1:12, .Label = c("January", 
"February", "March", "April", "May", "June", "July", "August", 
"September", "October", "November", "December"), class = "factor"), 
    diff = c(167916.47, 58945.82, 432269.2, 532863.2, -434494, 
    -493142.3, -50919.75, -207215.3, -278524.84, -77664.68, 161101.79, 
    144261.69), signal = c("pos", "pos", "pos", "pos", "neg", 
    "neg", "neg", "neg", "neg", "neg", "pos", "pos")), row.names = c(NA, 
-12L), class = c("tbl_df", "tbl", "data.frame"))

enter image description here

When 'plotting' the data without the geom_area(aes(fill = signal)), the graph comes out correct:

enter image description here

Then when I use the argument fill to try to fill in positive and negative with different colors

dados %>% 
  ggplot(aes(x = month, y = diff, 
             group = 1))+
  geom_area(aes(fill = signal))

get the following error: Erro: Aesthetics can not vary with a ribbon.

Did anyone know where the bug is? I tried with different data of these (with continuous variable on the X axis) and I got it, but not with these. Thank you.

1 answer

-1

You need the parameter group when using factors on the chart so that geom_area does not interpret each factor as a different group. The doc in this link has an example with geom_line.

To get the effect you want, it is necessary to divide the data into groups, as explained here.

In your case, you only have 1 group, which makes the situation easier. But this graph can get complicated if you had multiple groups with alternating positive and negative values. There’s a good discussion on this one thread.

  • thanks for the reply, I tried to play here, from my data, and at first did not come out. I will try to find out where is the error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.