r-lib / svglite

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

Squashed legend with ggplotGrob #61

Closed nathanwebb closed 8 years ago

nathanwebb commented 8 years ago

I'm not sure if this is a bug with my code, or svglite, and I'd really appreciate some help with this. I have a long function that needs to use grid graphics and grobs to format everything nicely, and after switching to svglite, the legends have become all squashed.

Here's a minimal example. The legends are squashed only if ggplotGrob is called before svglite and dev.off(), while base svg (example 4) didn't have that problem. In the second output file, the legends have become squashed together and are overlapping slightly. As the category names become longer, this becomes more of an issue as well.

library(ggplot2)
library(svglite)
library(grid)

p <- ggplot(head(diamonds, 100), aes(carat, price, col = cut)) +
  geom_point() +
  theme(legend.position = 'bottom') +
  theme(legend.title = element_blank())

pg <- ggplotGrob(p)

# works
svglite(file="test_svglite_1.svg")
  grid.draw(ggplotGrob(p))
dev.off()

# doesn't work
svglite(file="test_svglite_2.svg")
  grid.draw(pg)
dev.off()

# works with svglite
svglite(file="test_svglite_3.svg")
  inner_grob <- ggplotGrob(p)
  grid.draw(inner_grob)
dev.off()

# works with base svg
svg(file="test_svglite_4.svg")
  grid.draw(pg)
dev.off()