You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Close Contours Correctly for geom='polygon' in stat_contour #2534
@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.
(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!)
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).
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!
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 😢 )
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.
coord_map() can apply a variety of projections (supported by the mapproject package). Alternatively, Bob Rudis made thiscoord_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. :(
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.
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.
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.
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 152df1<- 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)
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.
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.)
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.
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.
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.
Activity
mdsumner commentedon Apr 26, 2018
(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!)
eliocamp commentedon Apr 26, 2018
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).
mdsumner commentedon Apr 26, 2018
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!
eliocamp commentedon Apr 26, 2018
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'sgeom_contour()(or, IMHO better still, add them togeom_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 😢 )mdsumner commentedon Apr 26, 2018
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.
eliocamp commentedon Apr 26, 2018
coord_map()can apply a variety of projections (supported by the mapproject package). Alternatively, Bob Rudis made thiscoord_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. :(
brodieG commentedon Apr 27, 2018
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.
eliocamp commentedon Apr 27, 2018
The polish is needed whether or not Hadley wants to incorporate it into ggplot2 proper instead of as an extension, though. 😆
hadley commentedon Apr 27, 2018
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
contourPolysor 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.
Draw correctly with stat_contour_fill
clauswilke commentedon Dec 26, 2018
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.
clauswilke commentedon Dec 27, 2018
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.Created on 2018-12-27 by the reprex package (v0.2.1)
mdsumner commentedon Dec 28, 2018
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.
29 remaining items
mdsumner commentedon Jan 8, 2019
This is great! I was confusing myself with grid.raster, but I'll just avoid that and mix base and grid graphics for testing.
clauswilke commentedon Jan 24, 2019
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.)
Created on 2019-01-24 by the reprex package (v0.2.1)
mdsumner commentedon Jan 24, 2019
Gee nice one, I look forward to seeing how you did that - but are these non overlapping regions? (I'll check, just wondering )
clauswilke commentedon Jan 24, 2019
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.
Created on 2019-01-24 by the reprex package (v0.2.1)
mdsumner commentedon Jan 24, 2019
You know I'm going to steal this and use it a lot everywhere
mdsumner commentedon Jan 24, 2019
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.
clauswilke commentedon Jan 24, 2019
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.
mdsumner commentedon Jan 25, 2019
ping @SymbolixAU also has done a lot of work towards an "sf-builder" from various forms
clauswilke commentedon Jan 25, 2019
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.
brodieG commentedon Jan 25, 2019
Should we close this issue in favor of "integrate
ggisoband"? Or leave it open until that is actually done?clauswilke commentedon Jan 25, 2019
I think the right issue to keep open is #3044.
brodieG commentedon Jan 26, 2019
I'll close this one then.
lock commentedon Jul 25, 2019
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/