How can I make geom_area() leave a gap for missing values?

前端 未结 1 1184
日久生厌
日久生厌 2021-01-18 05:53

When I plot using geom_area() I expect it to perform a lot like geom_bar(), but I\'m a little perplexed by this behavior for missing values.

<
相关标签:
1条回答
  • 2021-01-18 06:38

    It seems that the problem has to do with how the values are stacked. The error message tells you that the rows containing missing values were removed, so there is simply no gap present in the data that your are plotting.

    However, geom_ribbon, of which geom_area is a special case, leaves gaps for missing values. geom_ribbon plots an area as well, but you have to specify the maximum and minimum y-values. So the trick can be done by calculating these values manually and then plotting with geom_ribbon(). Starting with your data frame test, I create the ymin and ymax data as follows:

    test$ymax <-test$y
    test$ymin <- 0
    zl <- levels(test$z)
    for ( i in 2:length(zl) ) {
       zi <- test$z==zl[i]
       zi_1 <- test$z==zl[i-1]
       test$ymin[zi] <- test$ymax[zi_1]
       test$ymax[zi] <- test$ymin[zi] + test$ymax[zi]
    }
    

    and then plot with geom_ribbon:

    ggplot(test, aes(x=x,ymax=ymax,ymin=ymin, fill=z)) + geom_ribbon()
    

    This gives the following plot:

    enter image description here

    0 讨论(0)
提交回复
热议问题