3
votes

I have data of two time series that I would like to plot together. The x-axis will be date and the y-axis will be a line graph of series 1, while the point sizes will be scaled based on the numeric value of series 2. However, when series 2 = 0, I would like ggplot to not display a point at all. I've tried setting the range of point sizes from a minimum of 0, but it still displays points for values of 0.

Here's code to reproduce the problem:

Dates = c("2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06")
Dates = as.Date(Dates)
Series1 = c(0,2,8,5,3,1)
Series2 = c(0,0,5,0,10,5)

df = data.frame(Dates, Series1, Series2)
ggplot(data = df)+
   geom_line(aes(x=Dates, y = Series1))+
   geom_point(aes(x=Dates, y = Series1, size = Series2))+
   scale_size_continuous(range = c(0, 5))

This produces the following graph: PointSize=0 Displayed

How can I make ggplot2 not create a point when Series2 = 0, but still display the line? I also tried replacing 0's with NA's for Series2, but this results in the plot failing.

2
Maybe there's a difference in how you & I are viewing or saving this, because with your code, I've got points at size 0 that don't show. Not sure why they'd look different; maybe different resolution? But data viz nerds would argue that you should scale to area, not radius, which is why scale_size_area takes just a max size in order to put 0 values at a size 0camille

2 Answers

3
votes

You can change the minimum value to a negative one:

ggplot(data = df) +
  geom_line(aes(x = Dates, y = Series1))+
  geom_point(aes(x = Dates, y = Series1, size = Series2))+
  scale_size_continuous(range = c(-1, 5)) 

In case you do not want the legend to include 0 you can add breaks:

scale_size_continuous(range = c(-1, 5), breaks = seq(2.5, 10, 2.5)) 

enter image description here

1
votes

Another option is to make use of alpha to turn size == 0 points invisible. We set alpha in the aes to the logical expression Series2 == 0, and then use scale_alpha_manual to set values to 1 if FALSE and 0 (invisible) if TRUE:

ggplot(data = df)+
    geom_line(aes(x=Dates, y = Series1))+
    geom_point(aes(x=Dates, y = Series1, size = Series2, alpha = Series2 == 0))+
    scale_size_continuous(range = c(1, 5)) +
    scale_alpha_manual(values = c(1,0)) +
    guides(alpha = FALSE)     # Hide the legend for alpha

enter image description here