1
I have a DF
with 4 columns: data
, original
, previsto
and change
. The variable change
indicates whether the values of the series original
are positive or negative, to plot on the chart in green and red respectively. I tried to use the geom_area
, but the graph stays that way:
How to fix this problem of having the green line where it was to have only red and vice versa?
My code:
library(tidyverse)
data %>%
filter(variaveis == c("diferenca.em.pontos")) %>%
mutate(change = ifelse(value > 0, "positive", "negative")) %>%
ggplot(aes(x = Período, y = value, fill = change)) +
geom_area() +
geom_hline(yintercept = 0)
Man dput
:
data <- structure(list(Período = structure(c(13453, 13483, 13514, 13545,
13573, 13604, 13634, 13665, 13695, 13726, 13757, 13787, 13818,
13848, 13879, 13910, 13939, 13970, 14000, 14031, 14061, 14092,
14123, 14153, 15918, 15949, 15979, 16010, 16040, 16071), class = "Date"),
variaveis = structure(c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L), .Label = c("Brasil", "Brasil.predicted",
"Brasil.nivel", "Brasil.predicted.nivel", "diferenca.em.pontos"
), class = "factor"), value = c(28.5307986472031, 22.8246389177625,
16.3033135126875, 6.52132540507499, 4.07582837817188, -12.2274851345156,
-10.5971537832469, -8.96682243197813, -6.521325405075, -4.89099405380624,
-11.4123194588812, -20.3791418908594, -8.96682243197812,
-10.5971537832469, -9.7819881076125, -6.521325405075, 0,
-8.15165675634375, -27.7156329715687, -43.2037808086219,
-34.2369583766437, -26.9004672959344, -17.9336448639562,
-38.3127867548156, -18.7488105395906, -25.2701359446656,
-21.1943075664937, -14.6729821614187, -8.15165675634375,
0.815165675634374), change = c("positive", "positive", "positive",
"positive", "positive", "negative", "negative", "negative",
"negative", "negative", "negative", "negative", "negative",
"negative", "negative", "negative", "negative", "negative",
"negative", "negative", "negative", "negative", "negative",
"negative", "negative", "negative", "negative", "negative",
"negative", "positive")), row.names = c(1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L,
19L, 20L, 21L, 22L, 23L, 24L, 82L, 83L, 84L, 85L, 86L, 87L), class = "data.frame")
Thanks for the solution! But when running the code to generate the
new_df
, returned the errorError in 1:(nrow(data) - 1) : argumento de comprimento zero
.– Alexandre Sanches
@Alexandresanches What is that
nrow(data)
gives?– Rui Barradas
Returns 825 lines.
– Alexandre Sanches
@Alexandresanches I ran the code again, in a new session R, and no error.
1:(nrow(data) - 1)
gives a vector of length 824?– Rui Barradas
I got the desired result by adding
tidyr::complete(change, Período, fill = list(value = 0)) %>%
.– Alexandre Sanches