Search code examples
rggplot2raster

Use plot result as an overlay: remove legend and background and export a tiff / png


I would like to create a plot of wind directions displayed by arrows for several points.

This plot should have no legend and no background since I would like to export it as png and use it as overlay in further workflow.

I have an example data fame with 10 points (lon, lat) and wind directions in degrees.

Currently my plot looks like this:

enter image description here

I would like to:

  1. extend the plot to the size of

    3.604383, 14.60482, 47.07157, 54.73807 (xmin, xmax, ymin, ymax)

and

  1. remove axis and background so I can export it as png or tiff or a raster with only arrows displayed.

Here is my current approach:

library(ggplot)

wind_data<-
structure(list(lon = c(8.87312091729266, 8.71871388830953, 10.5679127453358, 
10.7216122406487, 10.4141464047873, 10.5679127453358, 10.1064188710028, 
11.3357135330171, 11.4890576651767, 11.1822955254471), lat = c(54.6482360923283, 
54.5584019137964, 54.2888913181823, 54.2888913181823, 54.1990517614177, 
54.1990517614177, 54.0193686018903, 53.6599860593553, 53.6599860593553, 
53.5701370357575), dd = c(238, 235, 238, 232, 232, 236, 239, 
240, 240, 240)), class = "data.frame", row.names = c(NA, -10L





 p<-ggplot(wind_data, aes(x = lon, y = lat)) +
  geom_segment(aes(xend = lon + 0.08, yend = lat + 0.08),
               arrow = arrow(length = unit(0.1, "cm")), size = 0.25)   # Make the line segments 0.25 mm thick

p + theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
                            panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),legend.position="none")
  

I tried to set the size of the plot by using

coord_cartesian(xlim = c(3.604383, 14.60482), ylim = ( 47.07157, 54.73807 ))

and removing legend

legend.position="none"

but it does not seem to work.


Solution

  • Besides the issue with not re-assignning to a variable after adjusting the limits and theme options a quick and easy approach to get rid of all non-data ink would be to use theme_void() instead of removing the theme elements one by one. However, one has to be aware that doing so will also remove e.g. the plot margins. But if needed adding them back in is still easily achieved by using e.g. + theme(plot.margin = margin(5.5, 5.5, 5.5, 5.5, unit = "pt")) for the default margins.

    library(ggplot2)
    
    p <- ggplot(wind_data, aes(x = lon, y = lat)) +
      geom_segment(aes(xend = lon + 0.08, yend = lat + 0.08),
        arrow = arrow(length = unit(0.1, "cm")), size = 0.25
      ) + 
      coord_cartesian(xlim = c(3.604383, 14.60482), ylim = c( 47.07157, 54.73807 )) +
      theme_void()
    
    p