joemienko joemienko - 3 months ago 7
R Question

Is it possible to achieve base-r plot `type=b` functionality in ggplot2?

Base

plot()
functionality allows one to set
type='b'
and get a combined line and point plot in which the points are offset from the line segments

plot(pressure, type = 'b', pch = 19)


enter image description here

I can easily create a ggplot with lines and points as follows.

ggplot(pressure, aes(temperature, pressure)) +
geom_line() +
geom_point()


enter image description here

The lines, however, run right up to the points. I can envision a way that I might hack together something like
type='b'
functionality using other geoms (e.g.
geom_segment()
?), but I am wondering if there is a more direct way to accomplish this with
geom_line()
and
geom_point()
.

Answer

A slightly hacky way of doing this is to overplot a small black point on a larger white point:

ggplot(pressure, aes(temperature, pressure)) + 
  geom_line() +
  geom_point(size=5, colour="white") + 
  geom_point(size=2) + 
  theme_classic() +
  theme(panel.background = element_rect(colour = "black"))

In addition, following Control point border thickness in ggplot, in version 2.0.0 of ggplot2 it's possible to use the stroke argument of geom_point to control the border thickness, so the two geom_points can be replaced by just (e.g.) geom_point(size=2, shape=21, fill="black", colour="white", stroke=3), eliminating the need to overlay the points.

enter image description here

Comments