Skip to content

Close Contours Correctly for geom='polygon' in stat_contour #2534

Closed

Description

@brodieG

Currently contours that end at the edges of the domain are not closed as one would expect, e.g.:

library(reshape2)
library(ggplot2)

ggplot(melt(t(volcano)), aes(x=Var1, y=Var2, z=value, fill=..level..)) +
  stat_contour(geom='polygon')

Produces:
screen shot 2018-04-26 at 8 37 40 am

Closed issue #1066 is related.

@eliocamp has a potential fix that involves expanding the grid to create a margin of sorts and setting all the values there to the mean of the z values so that the contours will close naturally.

@mdsumner has a work-around using using countourPolys::fcountour which if I understand correctly computes all the sub-polygons required to get the full contour working, and plots them all. I haven't actually run this so I may be misunderstanding. Scaling is likely an issue, and there is the issue that we're faking a large polygon with lots of little ones.

Ideally we would actually modify the contour function so that it internally closes the contour, but that is likely a fair bit more difficult to do.

Another option suggested by @hadley in #1066 is to patch up the output of contourLines rather than tricking countourLines to close the contours by expanding the range. This seems slightly cleaner, but I'm not sure the final result is actually any better than @eliocamp's solution and is more work relative to where we are today.

Activity

  1. mdsumner commented on Apr 26, 2018

    @mdsumner

    (The description of my approach is accurate, and I still have use for it in other contexts - filled contours as polygon objects being the obvious one, and I can make it more efficient - but I agree the solution here is a much better fit for the problem as it stands. Thanks!)

  2. eliocamp commented on Apr 26, 2018

    @eliocamp
    Contributor

    It would be nice to actually benchmark @mdsumner's solution against mine, because I've just tried it with a single field and is not much slower (admitedly, is a rather low resolution field).

    My solution has to do a lot of work to get things right. In addition to extend the values at the edges, it needs to assign the "inner value" of the contours, order them by area and then also fix a nasty problem I encountered in some datasets in which seemingly closed contours are actually made up of hundreds of small lines. I also think the code can be optimised.

    The whole thing is quite nasty and inelegant, and while it works perfectly for my work in meteorology, I don't know how reliable it could be with noisier datasets. It also has the rather annoying limitation that it only works for rectangular domains. I tried to apply the same principle to other shapes, but the contours get distorted at the edges. It also has problem with missing values inside the domain (I hack that infilling with the mean and letting the user mask those points).

    I don't know the inner workings of @mdsumner's solution to tell if it works with non-rectangular domains or how it handle missing values (I couln't make it work right out the gate, but I might be doing something wrong).

  3. mdsumner commented on Apr 26, 2018

    @mdsumner

    I intend to do all that exploration, it's been a very rich area of learning for me and I'm not done 😀 - I also wanted to show some detailed examples with @eliocamp's approach, because it produced a good result on a lot of complicated raster data (volcano is a very simple boundary scenario, though it's a nice test of nested polygons in holes with the crater).

    For ggplot2 I'd expect this is best submitted as a PR, and I'm happy to help with that if needed. But, I did want to set up a few good examples, and actually explore this more.

    Interestingly, you can get correctly nested polygons using sf::st_polygonize, but they are returned in a way that is not simple to reconstruct as proper objects (it comes out as a GEOMETRYCOLLECTION, and the nesting is correct but the actual holes aren't identified as such, and are repeated - i.e. the logic is all there but the alg doesn't take responsibility for what was intended).

    That's a long way of saying I have a lot more to offer but I'm not ready, but very happy to see this explored in such productive detail!

  4. eliocamp commented on Apr 26, 2018

    @eliocamp
    Contributor

    If your solution has some use cases that mine does not work with (for example, your approach is compatible with transparency), I don't see why both cannot be added in some way (as separate stats/geoms or as parameters in the same geom). Although I still don't understand why your polygons can be reprojected and mine don't.

    I think before I can submit a PR I need to polish the code, translate it from data.table to dplyr and, if possible, optimise it. Also, metR's geom_contour_fill() has other functionalities, like periodic domains and using a function to determine breaks that would have to be removed in order to make it consistent with ggplot's geom_contour() (or, IMHO better still, add them to geom_contour()). Of course rewriting old code is a lot less fun than creating new geoms that can help me with my work, so it's harder for me to sit down an do it 🙃 . (Also, it would be hard to say goodbye to my first geom that also started my first package 😢 )

  5. mdsumner commented on Apr 26, 2018

    @mdsumner

    Ah I'd forgotten about the data.table dependency and so on. there's no urgency to get this into ggplot2 from my perspective.

    The only thing about reprojection is that given the gg pipeline there's no way to reproject after the contouring and fill is done for this (is there?), and the input has to be a regular matrix (with expanded coordinates) - so improvements could be i) allow the contouring algorithm to run in index space, and then look up real coordinates after the lines are formed or ii) actually build the objects as polygons and keep independent, and plot with geom_polygon. gg doesn't have a standard + coord_sys() to transform the plot that works for any data afaik, there's no systems for keeping/changing metadata on pairs of columns.

    Also re i) there's no real affine transform support for a matrix, it re-infers this regularity from explicit coordinates in the contour alg (and in geom_raster) so you can't abstract from a regular indexed grid to a curvilinear mesh, although it's totally straightforward for this case outside the grammar.

    Anyway, I think we can safely keep this off the task list of the gg team for now - but if it generates discussion here then all good.

  6. eliocamp commented on Apr 26, 2018

    @eliocamp
    Contributor

    coord_map() can apply a variety of projections (supported by the mapproject package). Alternatively, Bob Rudis made this coord_project() that uses the proj4 system. According to his post, it has some limitations, but seems workable.

    The rest of your explanation really went over my head. I'm afraid I'm not that versed in projections and matrix operations. :(

  7. brodieG commented on Apr 27, 2018

    @brodieG
    ContributorAuthor

    I would probably hold off on waiting to see what @hadley is amenable to before you put any work into polishing things though. I imagine that's your plan, but just in case, would be a shame to do a bunch of work that ends up not meeting his requirements.

  8. eliocamp commented on Apr 27, 2018

    @eliocamp
    Contributor

    The polish is needed whether or not Hadley wants to incorporate it into ggplot2 proper instead of as an extension, though. 😆

  9. hadley commented on Apr 27, 2018

    @hadley
    Member

    To get into ggplot2, I need an implementation that is clean (i.e. I can actually understand it) and at least reasonably performant (so it doesn't affect existing plot speed). I suspect the fix is sufficiently complicated that it's better to put it in a separate package (maybe contourPolys or similar), which ggplot2 can then depend on.

    An ideal fix would be to reimplement the contouring from scratch in C, but I recognise that the effort required to do so is probably not worth the result.

  10. added
    feature
    on Apr 27, 2018
  11. clauswilke commented on Dec 26, 2018

    @clauswilke
    Member

    I just made a related comment on issue #3044 (comment), but it fits better here: The marching squares algorithm for contouring looks reasonably straightforward and is well explained on wikipedia: https://en.wikipedia.org/wiki/Marching_squares I believe the current contouring code uses that algorithm also, but it's not well documented.

    It would make more sense to reimplement that from scratch (specifically the version for filled contours) than to try to get the current contouring code to cooperate with filled polygons.

  12. clauswilke commented on Dec 27, 2018

    @clauswilke
    Member

    I wanted to see what would be required to implement the marching squares, so I went ahead and wrote a basic implementation, available here: https://gist.github.com/clauswilke/fc9431336e35a55db67f4176160428b6
    It is currently at a stage similar to @mdsumner's solution, in that it produces many small line segments or polygons rather than concatenated lines or merged polygons. However, it's already useful for plotting, and because we're building the line segments and polygons from scratch we know exactly how they relate to previous line segments and polygons and hence merging will be reasonably easy.

    Performance is on-par with grDevices::contourLines(), maybe about 20% slower, but that may well be simply because my implementation builds a data frame at the end.

    Rcpp::sourceCpp("contour_lines.cpp")
    
    library(ggplot2)
    
    contour_lines <- function(m, level = NULL) {
      if (is.null(level)) {
        level <- scales::pretty_breaks(10)(m)
      }
      purrr::map_dfr(level, ~single_contour_lines(1:ncol(m), nrow(m):1, m, .x))
    }
    
    # example of contour lines like current `geom_contour()`
    
    df <- contour_lines(volcano)
    ggplot(df, aes(x = x0, y = y0, xend = x1, yend = y1, color = level)) + 
      geom_segment() +
      scale_color_viridis_c()

    # example of two contour bands, one from 120 to 140 and one from 150 to 152
    
    df1 <- single_contour_bands(1:ncol(volcano), nrow(volcano):1, volcano, 120, 140)
    df2 <- single_contour_bands(1:ncol(volcano), nrow(volcano):1, volcano, 150, 152)
    df3 <- contour_lines(volcano, level = c(120, 140, 150, 152))
    ggplot(mapping = aes(x, y, group = id)) + 
      geom_polygon(data = df1, color = "lightblue", fill = "lightblue") +
      geom_polygon(data = df2, color = "tomato", fill = "tomato") +
      geom_segment(data = df3, aes(x = x0, y = y0, xend = x1, yend = y1), size = 0.2, inherit.aes = FALSE)

    # benchmark comparison to grDevices::contourLines()
    
    microbenchmark::microbenchmark(
      grDevices::contourLines(1:ncol(volcano), 1:nrow(volcano), volcano, levels = 120),
      single_contour_lines(1:ncol(volcano), 1:nrow(volcano), volcano, 120),
      single_contour_bands(1:ncol(volcano), 1:nrow(volcano), volcano, 120, 140)
    )
    #> Unit: microseconds
    #>                                                                                   expr
    #>  grDevices::contourLines(1:ncol(volcano), 1:nrow(volcano), volcano,      levels = 120)
    #>              single_contour_lines(1:ncol(volcano), 1:nrow(volcano), volcano,      120)
    #>         single_contour_bands(1:ncol(volcano), 1:nrow(volcano), volcano,      120, 140)
    #>      min       lq     mean   median       uq      max neval
    #>  274.263 338.5460 521.3048 395.7465 522.5410 8337.085   100
    #>  352.676 390.1815 473.0014 440.7035 498.1675 1498.814   100
    #>  348.136 441.4350 642.6149 599.7350 716.5120 2476.798   100

    Created on 2018-12-27 by the reprex package (v0.2.1)

  13. mdsumner commented on Dec 28, 2018

    @mdsumner

    Excellent! There's a bug or two in filled.contour (it leaves overlaps but not noticeable because it only plots), so this will be neat for comparison and getting control.

  14. 29 remaining items

  15. mdsumner commented on Jan 8, 2019

    @mdsumner

    This is great! I was confusing myself with grid.raster, but I'll just avoid that and mix base and grid graphics for testing.

  16. clauswilke commented on Jan 24, 2019

    @clauswilke
    Member

    Since we don't currently have good support for polygons with holes in ggplot2, I decided to write some code that can convert isobands to sf objects. This means you can reproject your contour bands as desired. The conversion is quite a bit slower than the initial contouring, but still takes only about 2 seconds for a realistic dataset.

    (My secret goal is to be able to animate contours. I think this is possible now via the sf route, though I haven't tried it yet.)

    library(ggplot2)
    library(isoband)
    library(raster)
    #> Loading required package: sp
    library(sf)
    #> Linking to GEOS 3.6.1, GDAL 2.1.3, PROJ 4.9.3
    
    # prepare data
    r <- raster(system.file("nc/reduced.nc", package = "stars"), varname = "sst")
    #> Loading required namespace: ncdf4
    z <- as.matrix(flip(r[[1]], "y"))
    z2 <- cbind(z[,91:180], z[,1:90]) # rearrange so world is centered around 0 meridian
    breaks <- pretty(range(z2, na.rm = TRUE), 15)
    n <- length(breaks)
    b <- isobands(xFromCol(r)-180, rev(yFromRow(r)), z2, breaks[1:(n-1)], breaks[2:n])
    bands <- iso_to_sfg(b)
    data <- st_sf(
      level = as.numeric(sub(":.*", "", names(bands))),
      geometry = st_sfc(bands, crs = 4326)
    )
    
    # longlat
    ggplot(data) + 
      geom_sf(aes(color = level, fill = level), alpha = 0.7) +
      scale_color_viridis_c(aesthetics = c("color", "fill"), option = "B", guide = "legend") +
      theme(legend.position = "bottom")

    # Robinson
    ggplot(data) + 
      geom_sf(aes(color = level, fill = level), alpha = 0.7) +
      coord_sf(crs = 54030) +
      scale_color_viridis_c(aesthetics = c("color", "fill"), option = "B", guide = "legend") +
      theme(legend.position = "bottom")

    # Goode
    ggplot(data) + 
      geom_sf(aes(color = level, fill = level), alpha = 0.7) +
      coord_sf(crs = "+proj=goode") +
      scale_color_viridis_c(aesthetics = c("color", "fill"), option = "B", guide = "legend") +
      theme(legend.position = "bottom")

    Created on 2019-01-24 by the reprex package (v0.2.1)

  17. mdsumner commented on Jan 24, 2019

    @mdsumner

    Gee nice one, I look forward to seeing how you did that - but are these non overlapping regions? (I'll check, just wondering )

  18. clauswilke commented on Jan 24, 2019

    @clauswilke
    Member

    Yes, non-overlapping. You can see this by calculating only every second band (see below).

    I had to write code that looks at all polygon boundaries and figures out which are outer boundaries and which are holes, since sf wants polygons that way. By the way, I can speed up the conversion by assuming the polygon boundaries are never in an inconsistent internal state. I just committed that fix and now conversion is basically instantaneous (60ms) for a dataset this size.

    library(ggplot2)
    library(isoband)
    library(raster)
    #> Loading required package: sp
    library(sf)
    #> Linking to GEOS 3.6.1, GDAL 2.1.3, PROJ 4.9.3
    
    # prepare data
    r <- raster(system.file("nc/reduced.nc", package = "stars"), varname = "sst")
    #> Loading required namespace: ncdf4
    z <- as.matrix(flip(r[[1]], "y"))
    z2 <- cbind(z[,91:180], z[,1:90]) # rearrange so world is centered around 0 meridian
    breaks <- pretty(range(z2, na.rm = TRUE), 15)
    n <- length(breaks)
    b <- isobands(
      xFromCol(r)-180, rev(yFromRow(r)), z2, 
      #breaks[1:(n-1)],
      breaks[2*(1:floor((n-1)/2))],
      #breaks[2:n]
      breaks[1+2*(1:floor((n-1)/2))]
    )
    bands <- iso_to_sfg(b)
    data <- st_sf(
      level = as.numeric(sub(":.*", "", names(bands))),
      geometry = st_sfc(bands, crs = 4326)
    )
    
    # longlat
    ggplot(data) + 
      geom_sf(aes(color = level, fill = level), alpha = 0.7) +
      scale_color_viridis_c(aesthetics = c("color", "fill"), option = "B", guide = "legend") +
      theme(legend.position = "bottom")

    # Robinson
    ggplot(data) + 
      geom_sf(aes(color = level, fill = level), alpha = 0.7) +
      coord_sf(crs = 54030) +
      scale_color_viridis_c(aesthetics = c("color", "fill"), option = "B", guide = "legend") +
      theme(legend.position = "bottom")

    # Goode
    ggplot(data) + 
      geom_sf(aes(color = level, fill = level), alpha = 0.7) +
      coord_sf(crs = "+proj=goode") +
      scale_color_viridis_c(aesthetics = c("color", "fill"), option = "B", guide = "legend") +
      theme(legend.position = "bottom")

    Created on 2019-01-24 by the reprex package (v0.2.1)

  19. mdsumner commented on Jan 24, 2019

    @mdsumner

    You know I'm going to steal this and use it a lot everywhere

  20. mdsumner commented on Jan 24, 2019

    @mdsumner

    Oh, and this is perfect for chaining GG aes() calls to declare arrangements from raw data, that end in spatial objects, not just graphics - lines and points are trivial but you just completed the circle.

  21. clauswilke commented on Jan 24, 2019

    @clauswilke
    Member

    Yes, that's the purpose. I plan to write this as a low-level, minimal-dependency library. In fact, I'm going to move the ggplot2 interface into a different package, so the only hard dependency for isoband is going to be Rcpp.

  22. mdsumner commented on Jan 25, 2019

    @mdsumner

    ping @SymbolixAU also has done a lot of work towards an "sf-builder" from various forms

  23. clauswilke commented on Jan 25, 2019

    @clauswilke
    Member

    The isoband package (https://github.com/clauswilke/isoband) now contains only the low-level code. I think I'll be able to submit a first version to CRAN soon.

    The ggplot2 interface now lives at https://github.com/clauswilke/ggisoband. The intent is to eventually integrate this code into ggplot2 proper, but a few design decisions still need to be hashed out, and it may have to wait until better polygon support in ggplot2.

  24. brodieG commented on Jan 25, 2019

    @brodieG
    ContributorAuthor

    Should we close this issue in favor of "integrate ggisoband"? Or leave it open until that is actually done?

  25. clauswilke commented on Jan 25, 2019

    @clauswilke
    Member

    I think the right issue to keep open is #3044.

  26. brodieG commented on Jan 26, 2019

    @brodieG
    ContributorAuthor

    I'll close this one then.

  27. lock commented on Jul 25, 2019

    @lock

    This old issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with reprex) and link to this issue. https://reprex.tidyverse.org/

  28. locked and limited conversation to collaborators on Jul 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurelayers 📈

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions