2

When I use geom_segment it's pixelized compared to a geom_abline. When I export to pdf with ggsave it's not vectorized.

geom_abline :

enter image description here

geom_segment :

enter image description here

Any idea how to solve this ?

Thanks

Nicolas Rosewick
  • 1,938
  • 4
  • 24
  • 42

1 Answers1

3

Yes, short answer: use annotate() instead of geom_segment().

Long(er) answer, whever you use geom_segment(), you are mapping every row in your data to the aesthetics (in this case coordinates) of the geom. Hence, they PDF from the geom_segment() contains nrow(your_data) lines on top of each other, giving that pixelated impression.

You can see this happening if you inspect the layer data of plots. Note especially the layer data of the second plot.

library(ggplot2)

defaults <- list(
  coord_cartesian(expand = FALSE),
  theme(axis.line = element_line(colour = "black"))
)


g <- ggplot(iris, aes(x, y)) +
  geom_abline(intercept = 0, slope = 1) +
  defaults
(layer_data(g))
#>   intercept slope PANEL group colour size linetype alpha
#> 1         0     1     1    -1  black  0.5        1    NA

g <- ggplot(iris, aes(x, y)) +
  geom_segment(x = 0, xend = 1, 
               y = 0, yend = 1) +
  defaults
(head(layer_data(g)))
#>   PANEL group colour size linetype alpha x y xend yend
#> 1     1    -1  black  0.5        1    NA 0 0    1    1
#> 2     1    -1  black  0.5        1    NA 0 0    1    1
#> 3     1    -1  black  0.5        1    NA 0 0    1    1
#> 4     1    -1  black  0.5        1    NA 0 0    1    1
#> 5     1    -1  black  0.5        1    NA 0 0    1    1
#> 6     1    -1  black  0.5        1    NA 0 0    1    1

g <- ggplot(iris, aes(x, y)) +
  annotate("segment", x = 0, xend = 1, y = 0, yend = 1) +
  defaults
(layer_data(g))
#>   x xend y yend PANEL group colour size linetype alpha
#> 1 0    1 0    1     1    -1  black  0.5        1    NA

Created on 2020-10-01 by the reprex package (v0.3.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63