r-lib / svglite

A lightweight svg graphics device for R
https://svglite.r-lib.org
180 stars 39 forks source link

`geom_rect` disappears when saving plot #160

Closed emstruong closed 1 year ago

emstruong commented 1 year ago

Related to ggplot2::ggsave.

Code

library(ggplot2)
library(svglite)

set.seed(123)

df <-
  data.frame(
    x = rpois(300, 3),
    y = c(rbinom(100, 1, .3), rbinom(100, 1, .5), rbinom(100, 1, .7)),
    group = factor(rep(c("a", "b", "c"), each = 100)) 
  )

loghistGraph<-ggplot(df, aes(xmin = x, xmax = x, ymin = rep(0, nrow(df)), ymax = rep(nrow(df)), color = group)) +
    geom_rect(size = 4, position = position_dodge(.3))

# Works
grDevices::svg("DefaultSvgWorks.svg")
print(loghistGraph)
dev.off()
#> png 
#>   2

# Doesn't work
svglite("svgliteBug.svg")
print(loghistGraph)
dev.off()
#> png 
#>   2

Created on 2022-12-26 by the reprex package (v2.0.1)

Attached are the two plots I get

Using svg() DefaultSvgWorks

Using svglite() svgliteBug

thomasp85 commented 1 year ago

If you open the svg file you can see that it contains the requested rects as expected. My guess is that because you are plotting rects with 0 width some sag renderers decide to not show these irrespective of whether they have a stroke. That is not the fault of svglite, though. The svg() device doesn't have this because it encodes everything as a path meaning that renderers can't make these optimisations.