简体   繁体   中英

possible bug in geom_ribbon

i was hoping to plot two time series and shade the space between the series according to which series is larger at that time.

here are the two series-- first in a data frame with an indicator for whichever series is larger at that time

d1 <- read.csv("https://dl.dropbox.com/s/0txm3f70msd3nm6/ribbon%20data.csv?dl=1")

And this is the melted series.

d2 <- read.csv("https://dl.dropbox.com/s/6ohwmtkhpsutpig/melted%20ribbon%20data.csv?dl=1")

which I plot...

ggplot() + geom_line(data = d2,
                 aes(x = time, y = value, group = variable, color = variable)) +
         geom_hline(yintercept = 0, linetype = 2) +
         geom_ribbon(data = d1[d1$big == "B",],
                     aes(x = time, ymin = csa, 
                         ymax =  csb),
                         alpha  = .25,
                         fill = "#9999CC") +
         geom_ribbon(data = d1[d1$big == "A",],
                     aes(x = time, ymin = csb, 
                         ymax =  csa),
                     alpha  = .25,
                     fill = "#CC6666") +
         scale_color_manual(values = c("#CC6666" , "#9999CC"))

which results in...

由此产生的情节

why is there a superfluous blue band in the middle of the plot?

Here is a solution. I replaced data = d1[d1$big == "B",] in the first geom_ribbon function with:

data = rbind(d1[d1$big == "B",],
             d1[c((which(diff(as.numeric(d1$big)) == -1) + 1),
                  (which(diff(as.numeric(d1$big)) == 1))), ])

This is necessary since the first and last rows of d1$big == "B" sequences often contain different csa and csb values. As a result, there is a visible ribbon connecting the data. The above command uses the last rows before and the first rows after these sequences together with the data for the first ribbon. This problem does not exist for d1$big == "A" (the base for the second ribbon).

The complete code:

ggplot() +
 geom_line(data = d2,
           aes(x = time, y = value, group = variable, color = variable)) +
 geom_hline(yintercept = 0, linetype = 2) +
 geom_ribbon(data = rbind(d1[d1$big == "B",],
                          d1[c((which(diff(as.numeric(d1$big)) == -1) + 1),
                               (which(diff(as.numeric(d1$big)) == 1))), ]),
             aes(x = time, ymin = csa, ymax =  csb),
             alpha  = .25, fill = "#9999CC") +
 geom_ribbon(data = d1[d1$big == "A",],
             aes(x = time, ymin = csb, ymax =  csa),
             alpha  = .25, fill = "#CC6666") +
 scale_color_manual(values = c("#CC6666" , "#9999CC"))

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM