Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 point size by numeric: Do not display point when value = 0

Tags:

r

ggplot2

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.

like image 960
DJA Avatar asked Jun 03 '26 19:06

DJA


1 Answers

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

like image 139
erc Avatar answered Jun 06 '26 09:06

erc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!