Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 dotted lines for a subsection of a plot

Tags:

r

ggplot2

I have the following data frame

z = data.frame(x = seq(1,10),y = c(1,2,2,3,2,15,2,3,4,2))

To get a simple line plot is straight forward. For example this works.

p = ggplot() + geom_line(data=z,aes(x,y))

I now want to call out the fact that the data point with value 15 is an outlier. To do this, I would like to make the line connecting 5,2 to 6,15 and 7,2 dotted. Can this be done somehow in ggplot2?

like image 991
broccoli Avatar asked Feb 01 '26 21:02

broccoli


1 Answers

You could make two lines, one dotted for all data, then one solid that excludes the outlier point. This seems to work:

ggplot() + geom_line(data=z,aes(x,y), linetype="dotted") + geom_line(data=z, aes(x, replace(y, y==15, NA)))
like image 139
Dan M. Avatar answered Feb 03 '26 12:02

Dan M.