3

I've placed my legend horizontally (5 categories) below my barpchart, within r this works fine, but when I save my plot as a picture some categories from the legend disappear or are out of boundary of the plot/picture. I used ggsave("myPlot.png", p, units = "cm", dpi = 600) in which p represents my plot. Should I fix this within my ggplot call or within ggsave() and how? I want a smaller length of the complete legend box (in the final saved picture). I've included the picture, so you can see how the legend went wrong. Help is appreciated! Thank you.

enter image description here

Benjamin Telkamp
  • 1,451
  • 2
  • 17
  • 31
  • 2
    It looks like `ggsave`'s default dimensions are messing with the relative sizes of the plot elements, leading to a cut off legend. Try `ggsave("myPlot.png", p, units = "cm", dpi = 600, scale = 2)`, or even `scale = 3`. Or specify `width` and `height` arguments to control the overall output size. – jdobres Sep 29 '18 at 16:15
  • Playing with `width` and `height` works, just need to try a few times, thanks, if you here about an automatic option, I'm all ears. – Benjamin Telkamp Sep 29 '18 at 18:11

2 Answers2

2

save_plot() from the cowplot package avoids this

instead of:

ggsave("myPlot.png", p)

try:

save_plot("myPlot.png", p)

talialynn
  • 46
  • 1
  • 6
  • strangely, even if I use save_plot I get the cut off... is there anything else I can do? I also tried cowplot::save_plot(...) – canIchangethis Nov 14 '22 at 18:59
0

You can use theme(legend.box.margin = margin()) and pad the right margin so it doesn't get cut off. I had the same problem when combining plots using cowplot::plot_grid() and adding the legend separately.

David
  • 572
  • 3
  • 12
L word
  • 1
  • 1