trevorld / ggpattern

ggplot geoms with pattern fills
https://trevorldavis.com/R/ggpattern/dev/
Other
359 stars 18 forks source link

pattern not shown in legend in png, pdf... #53

Closed hansjun closed 2 years ago

hansjun commented 2 years ago

Hi,

I'm trying to export a ggplot-map (geom_sf_pattern).

My map uses the aes 'fill' and 'pattern_fill' with the same variable. For the legend I use scale_fill_manual and scale_pattern_fill_manual with the same names and labels. So I get one legend.

In the plot-window of RStudio everything looks fine. But when I try to export the map (as png or pdf..., with ggsave or png-dev.off) I get the following warning: 1: convert_polygon_sf_to_polygon_df(): Not POLYGON or MULTIPOLYGON: c("XY", "LINESTRING", "sfg")

And in the exported file the legend does not have stripes, only the map has them.

Thanks for your support!

trevorld commented 2 years ago

Your issue lacks a minimal, reproducible example...

{rstudioapi} has a savePlotAsImage() function to save the image in the plot-window of RStudio: https://rstudio.github.io/rstudioapi/reference/savePlotAsImage.html

hansjun commented 2 years ago

Thank you for your help. 'savePlotAsImage' works.

To solve the problem with ggsave here an example file (I hope you can use it). RStudio shows stripes in two legend entries (bottom left and top right), my png-file not.

ggpattern_plotlegend.zip

Here my skript: testplot <- ggplot(geodat_kgs_hole) + # Datensatz mit Ästhetik geom_sf_pattern(aes(pattern_fill = as.factor(KREISTYP), fill = as.factor(KREISTYP)), colour = "white", pattern_colour = NA) + # Kreiskarte scale_pattern_fill_manual(name = "Kreistyp", values = c("green", "orange", "green", "orange"), labels = c("Kreisfreie Großstaedte", "Staedtische Kreise", "Laendliche Kreise mit Verdichtungsansaetzen", "Duenn besiedelte laendliche Kreise")) + # Palette für pattern
scale_fill_manual(name = "Kreistyp", values = c("green", "green", "orange", "orange"), labels = c("Kreisfreie Großstaedte", "Staedtische Kreise", "Laendliche Kreise mit Verdichtungsansaetzen", "Duenn besiedelte laendliche Kreise")) + # manuelle Farbpalette für "fill" labs(title = "Kreistyp", # Überschrift, Beschriftungen x = NULL, y = NULL) + theme_classic() + # Layout theme(axis.text = element_blank(), # Entfernung Achsen axis.line = element_blank(), axis.ticks = element_blank(), plot.title = element_text(hjust = 0.5), # Position Diagrammtitel zentral legend.position = "bottom") + # Position Legende guides(pattern_fill = guide_legend(title.position = "top", ncol = 2)) # Legende formatieren

testplot

ggsave("Testplot_GitHub.png", testplot, width = 20, height = 29, units = "cm")

hansjun commented 2 years ago

I added pattern_spacing = 0.01 to geom_sf_pattern. Now everything works with ggsave. I don't get warnings and the stripes are visible in the legend of my png file...