我有一个DF
,其中有4列:date
,original
,predicted
和change
。我想制作一个面积图,根据change
列,负值是红色,正值是绿色。
我的代码:
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)
但是它的返回是这样的,绿色线在红色值上方,这是不应该发生的。我在做什么错了?
如果我使用geom_col
而不是geom_area
,则该图是正确的:
我的dput
:
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")
答案 0 :(得分:0)
与其尝试在同一个 geom_area() 函数中绘制所有内容,不如尝试使用它两次:一次用于正值,另一次用于负值。可能不是最好的解决方案,但它有效。
ggplot(dput) +
geom_area(aes(x=Período, y=ifelse(value<0, value,0)), fill="red") +
geom_area(aes(x=Período, y=ifelse(value>0, value, 0)), fill="green")
我希望这对你有帮助:)