Home > Mobile >  ggplot2 geom_pointline doesn't link centers of points
ggplot2 geom_pointline doesn't link centers of points

Time:10-12

I would like to create a plot with points and lines between them, but with spaces, in ggplot2, R. I have a shaded area in the plot, so some parts of points has gray and white background. I found lemon library with geom_pointline function.

ggplot(data = dt, aes(x = x, y = y))   
geom_ribbon(aes(ymin = min, ymax = max), fill = "gray", alpha = 0.35)  
geom_pointline(shape = 19, linecolor = "black", size = 4, color = "blue", distance = 2)

The result I get is shown below. As one can notice, the lines don't start and end in the middle of points, but rather at the top right and bottom left of the point. It gets even worse when I shorten the lines. I tried with many parameters but couldn't solve it. I would like the lines to start and end closer to the middle than it is now. Thanks in advance!

result

CodePudding user response:

If switching to an other package is an option for you then one option to achieve your desired result would be ggh4x::geom_pointpath whichs similar to geom_pointline adds some padding around points along a line or path. One drawback is that TBMK it has no option to set different colors for the points and the lines. A hack would be to draw the lines via ggh4x::geom_pointpath then add a geom_point on top of it.

Using some fake example data:

set.seed(123)

dt <- data.frame(
  x = seq(20, 160, 20),
  y = 1:8,
  min = 1:8 - runif(8),
  max = 1:8   runif(8)
)

library(ggplot2)
library(ggh4x)

ggplot(data = dt, aes(x = x, y = y))   
  geom_ribbon(aes(ymin = min, ymax = max), fill = "gray", alpha = 0.35)  
  geom_pointpath(shape = 19, size = 4, color = "black", mult = .25)  
  geom_point(shape = 19, size = 4, color = "blue")

  • Related