ggplot2正/负图不能干净利落地呈现

时间:2016-01-21 01:46:39

标签: r ggplot2

我试图像示例here那样复制一个顶部底部的情节,但它没有正确渲染(紫色系列有+ ve和-ve值,绿色是负数)凌乱的文物。我也在努力创建一个复制问题的玩具示例,所以我希望尽管我缺乏数据,但有人可以提供帮助

我的代码是:

negatives <- result[result$value < 0,]
positives <- result[result$value >= 0,]

ggplot() + 
  geom_area(data = negatives, aes(x = datetime, y = value, fill=variable)) +
  geom_area(data = positives, aes(x = datetime, y = value, fill=variable))

我的数据结构是:

dput(droplevels(head(result)))

structure(
list(
    datetime = structure(c(1421751900, 1421751900, 1421752200, 1421752200, 1421752500, 1421752500), class = c("POSIXct", "POSIXt"), tzone = ""), 
    variable = structure(c(1L, 2L, 1L, 2L, 1L, 2L), .Label = c("V-S-MNSP1", "VIC1-NSW1"), class = "factor"), 
    value = c(9, 80.106180098, 9, 77.719632578, 9, 84.158868934 )
), 
.Names = c("datetime", "variable", "value"), 
row.names = c(NA, 6L), 
class = "data.frame")

top/bottom plot

1 个答案:

答案 0 :(得分:0)

我发现了问题,我的数据点可以是正面的也可以是负面的。如果我没有为每个日期时间的每个变量赋值,那么堆叠似乎不起作用。所以不要这样做

negatives <- result[result$value < 0,]
positives <- result[result$value >= 0,]

我这样做

result$positive <- ifelse(result$value >= 0,result$value,0)
result$negative <- ifelse(result$value < 0,result$value,0)

ggplot(data = result) + 
  geom_area(aes(x = datetime, y = positive, fill=variable), position = 'stack') +
  geom_area(aes(x = datetime, y = negative, fill=variable), position = 'stack')

然后我的图表正确呈现

戴夫

相关问题