wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
650 stars 37 forks source link

Support `geom_richtext()` for sf plots #76

Open msberends opened 2 years ago

msberends commented 2 years ago

I kindly request geom_sf_richtext() 😄

This would bring the option to spatial analyses to print markdown in sf plots as well, for example to print datalabels with square kilometres and subsequent superscript.

Many thanks for the package, it should become part of ggplot2 as soon as possible as far as I'm concerned.

StuieT85 commented 2 years ago

I don't know if this would help but I was playing around, comparing the differences between geom_sf_label, geom_label and geom_richtext and this seems to work.

geom_sf_richtext <- 
function (mapping = aes(), data = NULL, stat = "sf_coordinates", 
          position = "identity", ..., parse = FALSE, nudge_x = 0, 
          nudge_y = 0, label.padding = unit(0.25, "lines"), label.r = unit(0.15, 
                                                                           "lines"), 
          label.size = 0.25, na.rm = FALSE, show.legend = NA, 
          inherit.aes = TRUE, fun.geometry = NULL) 
{
  if (!missing(nudge_x) || !missing(nudge_y)) {
    if (!missing(position)) {
      abort("Specify either `position` or `nudge_x`/`nudge_y`")
    }
    position <- position_nudge(nudge_x, nudge_y)
  }
  layer_sf(data = data, mapping = mapping, stat = stat, geom = GeomRichText, 
           position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
           params = list(label.padding = label.padding, 
                         label.r = label.r, label.size = label.size, na.rm = na.rm, 
                         fun.geometry = fun.geometry, ...))
}

It is probably missing something but I have tried it on a couple of maps and it has seemed to work for me.

I also agree that I think it should become part of ggplot2 too :)

msberends commented 2 years ago

Great solution, but GeomRichText unfortunately adds a border around the label, whereas ggplot2::GeomText doesn't. So I can't get this to work without a border around the labels. Any ideas?

I now have this map (just showing the Netherlands with province names and area in sq km), without using ggtext:

Screenshot 2022-01-22 at 22 40 54

It's a geom_sf_text() atop of a geom_sf_label(). The label only has a fill (with alpha), the text only has a colour.

And I'd of course like to show the exponent in superscript, but using GeomRichText gives me:

Screenshot 2022-01-22 at 22 41 04
msberends commented 2 years ago

We might need GeomRichText and GeomRichLabel here.

Also not sure why GeomRichText and GeomRichtext both exist.

msberends commented 2 years ago

Got it. Your geom_sf_richtext() should have the extra arguments label.colour = NA and fill = NA in the params list (to comply with ggplot2's definition of geom_sf_text and geom_sf_label).