Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible bug in geom_ribbon

Tags:

r

ggplot2

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...

the resulting plot

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

like image 537
tomw Avatar asked Oct 28 '12 04:10

tomw


1 Answers

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"))

enter image description here

like image 149
Sven Hohenstein Avatar answered Oct 07 '22 11:10

Sven Hohenstein