1

I have a time series that I'd like to plot using the polygon function as I want to create a shade between different time series. However, when calling polygon (), the function adds a line between the first and last point (in essence it connects the first and last point to finish the plot). I would like to know how to tell R not to join up the two. Slightly related questions have been posted (Line connecting the points in the plot function in R) but the solutions didn't help. Any help would be appreciated.

I have already tried several things, such as reordering the data like in the part below.

% ts_lb_vec is my time-series in vector format;

% x is a vector of time (2000 to 2015);

% I first call plot which plots x (time) with y (the time-series). This works fine;

plot(x, ts_lb_vec,type='n',ylim=c(-300,300), ylab="", xlab="")

But if I want to use the polygon function to use the shading capabilities, it draws the line and I have tried reordering the data (as below) to try to eliminate the problem but this is unsuccessful

polygon(x[order(x),ts_lb_vec[order(x)], xlim=range(x), ylim=range(ts_lb_vec))

I would just like R when calling the polygon function to not connect my first and last point (see image). The figure attached bellow was produced using the following code:

plot(x, ts_lb_vec,type='n', ylab="", xlab="")
polygon(x, ts_lb_vec)

enter image description here

Just to clarify, what I would like is for the space between two time series to be filled, hence why I need the function polygon. See image belowenter image description here

UseR10085
  • 7,120
  • 3
  • 24
  • 54
jb16006
  • 67
  • 1
  • 10
  • The ends has to connect, otherwise it isn't really a polygon, and no way to tell what area should be shaded. You have to decide _how_ you want the ends to be connected. – AkselA Aug 12 '19 at 23:15
  • OK, this makes sense but what I'd like is that the space between one timeseries and another is filled with a shade. I've attached a second image in the question to clarify. Thanks! – jb16006 Aug 12 '19 at 23:18

1 Answers1

1

I put together a solution using ggplot2.

The key step is drawing a separate polygon where the order of one of the curves is inverted to avoid the crossing over back to the start.

# simple example data
examp.df <- data.frame(time = seq_len(15), a  = c(1,2,3,4,5,5,5,4,3,2,4,5,6,7,8), b = c(2,4,5,6,7,8,7,6,6,5,6,4,3,2,1))

# the polygon is generated by inverting the curve b
polygon <- data.frame(time <- c(examp.df$time, rev(examp.df$time)), y.pos = c(examp.df$a, rev(examp.df$b)))

ggplot(examp.df) + 
  geom_polygon(data = polygon, aes(x = time, y = y.pos), fill = "blue", alpha = 0.25) + 
  geom_line(aes(x= time, y = a), size = 1, color = "red") + 
  geom_line(aes(x = time, y = b), size = 1, color = "green") + 
  theme_classic()

Which results in: two curves with a polygon in the middle

If you want to know more about ggplot2 this is a good introduction.

d.b
  • 32,245
  • 6
  • 36
  • 77
PPK
  • 186
  • 2
  • 7