Skip to content

Revisit Matplotlib Support for Plotting #840

Closed

Description

@philipc2

Activity

  1. rljacob commented on Jul 8, 2024

    @rljacob
    Member

    What I think users want is uxarray --> matplotlib without going through holoviews. Can we do that?

  2. rajeeja commented on Jul 8, 2024

    @rajeeja
    Contributor

    What I think users want is uxarray --> matplotlib without going through holoviews. Can we do that?

    May be issue a warning or something that points the users towards holoviews, we use it because of xarray support, interactive and ability to large datasets and utilize dask..

  3. rljacob commented on Jul 8, 2024

    @rljacob
    Member

    Many climate use cases involve making figures from scripts so interactive is not a requirement.

  4. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    Many climate use cases involve making figures from scripts so interactive is not a requirement.

    HoloViews isn't just used for interactive plots. It can be used with the Matplotlib backend to generate figures from scripts, as can be seen in #843

  5. xylar commented on Jul 9, 2024

    @xylar
    Collaborator

    @philipc2, we working on MPAS (Model for Prediction Across Scales) visualization have found HoloViews to be pretty counterintuitive, hard to configure and hard to get to behave as we need it to. The interactivity is not something we take advantage of very often, so that isn't a plus for us. The lack full integration of cartopy and projections seems to be a big downside for us. In addition, HoloViews has a very different interface form matplotlib (so a big learning curve and porting cost) and and is separated by many levels of (often poorly documented) code from the associated matplotlib calls. While we can sometimes use HoloViews plot figures that are "good enough" for debugging purposes, we have not had much luck when we try to incorporate them into our automated analysis pipeline or to make publication-quality figures.

    We are getting around this by writing our own code (planned for https://github.com/E3SM-Project/mosaic) to handle polygon collections directly with matplotlib and cartopy but not using HoloViews. Our plan is to develop this capability for a bit with MPAS meshes in mind but then to suggest it as an alternative approach for UXarray if and when we can demonstrate its success.

  6. whannah1 commented on Jul 9, 2024

    @whannah1

    The lack full integration of cartopy and projections seems to be a big downside for us.

    IMO this is the only issue that matters for wider adoption.

  7. xylar commented on Jul 9, 2024

    @xylar
    Collaborator

    The lack full integration of cartopy and projections seems to be a big downside for us.

    I know that GeoViews is supposed to take care of this but this hasn't been anywhere near seamless in your testing so far.

  8. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    Thanks for the feedback all!

    • We will look into better supporting UxDataArray.to_polycollection() and Grid.to_linecollection() methods (which we do currently roughly support, but have not done any testing since the last time we look at it with our 2023 SIParCS intern). We we look into getting some documentation into our User Guide on these methods. Our main reason for not moving forward with using Matplotlib directly was the less than ideal performance for visualizing high resolution grids.
    • Our Point plotting does support Cartopy projections, however our Polygon methods do not have projection support yet. We will look into getting better compatibility with GeoViews
  9. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    Here's a minimal example of plotting the grid using out to_linecollection() method.

    # Conversion to Line Collection
    lc = uxds.uxgrid.to_linecollection()
    
    plt.figure(figsize=(6, 4))
    ax = plt.axes(projection = ccrs.PlateCarree())
    ax.coastlines()
    ax.set_extent((-110, -50, 0, 40))
    ax.add_collection(lc)
    plt.title("Line Collection Plot")
    image
  10. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    Another example using our to_polycollection() method.

    pc, _ = uxds['SFCO2'][0].to_polycollection()
    
    pc.set_transform(ccrs.PlateCarree())
    plt.figure(figsize=(20, 10))
    ax = plt.axes(projection=ccrs.Robinson())
    pc.set_cmap("inferno")
    ax.add_collection(pc)
    ax.set_title("SFCO2 Poly Collection")
    ax.set_global()
    ax.set_extent((-180, 180, -90, 90), crs=ccrs.PlateCarree())
    plt.colorbar(pc)
    image
  11. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    Wondering if these to_polycollection and to_linecollection methods are sufficient as an interface for Matplotlib. We could consider adding an "alternative" .plot() method that uses Matplotlib directly, but this would require some significant work on our end. Could look something like.

    import uxarray as ux
    
    uxds = ...
    
    ux.set_plotting_backend("matplotlib")
    
    # use MPL
    uxds['t2m'].plot()
    
    ux.set_plotting_backend("holoviews")
    
    # use HoloViews 
    uxds['t2m'].plot()
  12. whannah1 commented on Jul 9, 2024

    @whannah1

    Another example using our to_polycollection() method.

    pc, _ = uxds['SFCO2'][0].to_polycollection()
    
    pc.set_transform(ccrs.PlateCarree())
    plt.figure(figsize=(20, 10))
    ax = plt.axes(projection=ccrs.Robinson())
    pc.set_cmap("inferno")
    ax.add_collection(pc)
    ax.set_title("SFCO2 Poly Collection")
    ax.set_global()
    ax.set_extent((-180, 180, -90, 90), crs=ccrs.PlateCarree())
    plt.colorbar(pc)

    I can kind of get this to work - but when I change things slightly I'm getting a blank plot or a single vertical line or flipped coordinates.

    Why are two projections (Robinson and PlateCarree) being used in that example?

  13. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    Why are two projections (Robinson and PlateCarree) being used in that example?

    pc.set_transform(ccrs.PlateCarree()) sets the original projection of the data we are working with, and ax = plt.axes(projection=ccrs.Robinson()) sets our destination projection

    I can kind of get this to work - but when I change things slightly I'm getting a blank plot or a single vertical line or flipped coordinates.

    There are indeed a few bugs with this; we haven't maintained it in over a year. Working on getting some fixes out right now. Wonder what changes you made?

  14. 15 remaining items

  15. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    @philipc2 the last example there seems to have a problem of data being cutoff. You should really use a different variable and maybe a brighter colormap to help make these issues more noticeable.

    Yeah, I'll create a better comparison soon. Really curious to why some projections work fine and others seem to fail though.

  16. andrewdnolan commented on Jul 9, 2024

    @andrewdnolan

    @philipc2 Awesome! Thanks for catching my mixup there.

    So, the next question / problem I have might be related to the projection problem that you and @whannah1 have brought up.

    Using the mpaso.IcoswISC30E3r5.20231120 mesh, @philipc2 how long does it take you to plot wtih projection other than ccrs.PlateCarree? For me it takes a really long time, using ccrs.RotatedPole it takes >11 minutes!

    I think this is because PolyCollections aren't really supported by cartopy. When you set the transform for the collection (e.g. collection.set_transform(transform)) it's using the matplotlib transform method, not caropty's methods for transforming coordinates.

    For those troublesome projections, I wonder if the problems would persist if you created QuadMesh collections, which are supported by cartopy, instead of PolyCollections. What mesh are you using for those plots? It'd be great to play around with those and see if I can better demonstrate what I mean.

  17. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    @philipc2 Awesome! Thanks for catching my mixup there.

    So, the next question / problem I have might be related to the projection problem that you and @whannah1 have brought up.

    Using the mpaso.IcoswISC30E3r5.20231120 mesh, @philipc2 how long does it take you to plot wtih projection other than ccrs.PlateCarree? For me it takes a really long time, using ccrs.RotatedPole it takes >11 minutes!

    I think this is because PolyCollections aren't really supported by cartopy. When you set the transform for the collection (e.g. collection.set_transform(transform)) it's using the matplotlib transform method, not caropty's methods for transforming coordinates.

    For those troublesome projections, I wonder if the problems would persist if you created QuadMesh collections, which are supported by cartopy, instead of PolyCollections. What mesh are you using for those plots? It'd be great to play around with those and see if I can better demonstrate what I mean.

    Let it run in the background and this is what I got. Usually it takes a bit more time to actually show up in the notebook though.

    image
  18. philipc2 commented on Jul 9, 2024

    @philipc2
    MemberAuthor

    I haven't use Matplotlib much for plotting unstructured grids. Wonder if there is a way to rasterize the PolyCollection, something similar to what Datashader does, since there is no point in plotting every polygon for such a high resolution grid.

  19. rajeeja commented on Jul 10, 2024

    @rajeeja
    Contributor

    I haven't use Matplotlib much for plotting unstructured grids. Wonder if there is a way to rasterize the PolyCollection, something similar to what Datashader does, since there is no point in plotting every polygon for such a high resolution grid.

    from matplotlib.collections import PolyCollection PolyCollection has a .set_rasterized(True) will this do it?

  20. andrewdnolan commented on Jul 10, 2024

    @andrewdnolan

    Hi @rajeeja!

    I think that only take effect when the figure is saved to a vector graphic format, see the the "Note" from matplotlib docs here: https://matplotlib.org/stable/gallery/misc/rasterization_demo.html

    But, I don't think the significant overhead when using a projection has to do with the rendering of each individual polygon. If that were the case, then there would be a similar overhead when using no projection (or projection == transform), which isn't the case (at least for me). When plotting the MPAS data with a PlateCarree projection it takes seconds, but using any other kind of projections it takes on the order of 5 minutes.

    I think this has to do with the way the geographic transform is used by PolyCollection, which isn't explicitly supported by cartopy (I think). I'm working on a demo with some cubed sphere data in order to demonstrate some timing differences when using PolyCollection versus QuadMesh, which is supported by cartopy. I'll be back in touch soon once that's worked out.

  21. rajeeja commented on Jul 10, 2024

    @rajeeja
    Contributor

    Hi @rajeeja!

    I think that only take effect when the figure is saved to a vector graphic format, see the the "Note" from matplotlib docs here: https://matplotlib.org/stable/gallery/misc/rasterization_demo.html

    But, I don't think the significant overhead when using a projection has to do with the rendering of each individual polygon. If that were the case, then there would be a similar overhead when using no projection (or projection == transform), which isn't the case (at least for me). When plotting the MPAS data with a PlateCarree projection it takes seconds, but using any other kind of projections it takes on the order of 5 minutes.

    I think this has to do with the way the geographic transform is used by PolyCollection, which isn't explicitly supported by cartopy (I think). I'm working on a demo with some cubed sphere data in order to demonstrate some timing differences when using PolyCollection versus QuadMesh, which is supported by cartopy. I'll be back in touch soon once that's worked out.

    Thanks for link, it might be that matplotlib optimizes some projections and not all or the support for other libraries in not optimized as you state.

  22. philipc2 commented on Jul 10, 2024

    @philipc2
    MemberAuthor

    I've also had similar performance issues with projecting polygons when using GeoViews, so it might be the case that applying projections to Polygons is simply more expensive than applying to to a QuadMesh or similar type of grid.

    I believe that projecting the data prior to creating a PolyCollection might be a better approach.

  23. philipc2 commented on Jul 10, 2024

    @philipc2
    MemberAuthor

    If we project before visualization, even if there is a moderate overhead, it would only be a one-time computation. Something like the following would be good to have for UXarray.

    uxgrid = ux.open_grid(...)
    
    # in-place projection
    uxgrid.set_projection("Robinson")
    
    # fluent projection (return a new Grid)
    uxgrid_rob = uxgrid.project("Robinson")
    
    # should now be able to plot without needing to apply any other projections
    uxgrid_rob.to_polycollection()
  24. andrewdnolan commented on Jul 10, 2024

    @andrewdnolan

    That's exactly what I'm doing in mosiac! Yeah I definitely think that's the best approach. Plus if you have multiple subplots (with the same projection), you don't have to do the same projection operation multiple time.

    Another benefit is if your doing it to the coordinate arrays, those are usually much smaller than the polygon arrays. Using MPAS variable names and just considering cell centered values as an example you'll have two coordinate arrays which are nCells long (i.e. lonCell and latCell), i.e 2*nCells values to transform. Whereas, for the polygon patches those will have dimensions nCells x maxEdges x 2, where maxEdges could be somewhere between 6 and 8 in practice. So by transforming the patches you'd be doing 6--8 times the work necessary to transform coordinates, c.f. transforming the coordinates array directly once.

  25. philipc2 commented on Jul 10, 2024

    @philipc2
    MemberAuthor

    That's exactly what I'm doing in mosiac! Yeah I definitely think that's the best approach. Plus if you have multiple subplots (with the same projection), you don't have to do the same projection operation multiple time.

    Another benefit is if your doing it to the coordinate arrays, those are usually much smaller than the polygon arrays. Using MPAS variable names and just considering cell centered values as an example you'll have two coordinate arrays which are nCells long (i.e. lonCell and latCell), i.e 2*nCells values to transform. Whereas, for the polygon patches those will have dimensions nCells x maxEdges x 2, where maxEdges could be somewhere between 6 and 8 in practice. So by transforming the patches you'd be doing 6--8 times the work necessary to transform coordinates, c.f. transforming the coordinates array directly once.

    One of the reasons we didn't move forward with supporting these types of projections early was our method of handling faces around the antimeridian. We use the [antimeridian](https://github.com/gadomski/antimeridian) package, which limited us to defining the antimeridian as +- 180 degrees with the standard PlatteCaree projection.

  26. andrewdnolan commented on Jul 10, 2024

    @andrewdnolan

    So took me a little while to come up with a working example, but here's a notebook with some timing info for PloyCollection versus QuadMesh. The big take away is:
    timing

    The timing if for the same quadrilateral mesh (w/ ~40,000 cells), but plotted with the PloyCollection and QuadMesh methods respectively. But, directly comparing those isn't really fair since QuadMesh is super optimized. So, I first get the inherent time difference between PloyCollection and QuadMesh, when not using map projected data (i.e. no GeoAxis). I then normalize the QuadMesh time by this inherent overhead, so the columns to really compare are the orange and green.

    For the projections tested PloyCollection is 150 time slower, when using a GeoAxis than QuadMesh (normalized). I believe this has to do with QuadMesh being explicitly supported by cartopy, where PloyCollection isn't.

    Pre-transforming the coordinates to the project used before PolyCollection creation is definitely one way circumvent this problem, it's what I'm doing to address this aswell in mosaic. But I wonder if at some point we'll need to open a PR in caropty directly to add support for PolyCollection's inorder to make this a bit more robust.

  27. philipc2 commented on Jul 11, 2024

    @philipc2
    MemberAuthor

    Thanks for the great timing chart! By projecting the coordinates before creating a PolyCollection, the execution time went down to under 4 seconds for me. Going to push these changes soon to the branch in #844

    %%time
    
    projection = ccrs.Orthographic()
    
    # create a Poly Array from a 1D slice of a face-centered data variable
    collection = uxds['temperature'].isel(Time=0, nVertLevels=0).to_polycollection(override=True, periodic_elements="exclude", projection=projection)
    
    pc = copy.deepcopy(collection)
    
    pc.set_antialiased(False)
    pc.set_cmap("viridis")
    
    fig, ax = plt.subplots(1, 1, figsize=(15,7), facecolor="w",
                           constrained_layout=True,
                           subplot_kw=dict(projection=projection))
    
    
    ax.coastlines()
    ax.add_collection(pc)
    ax.set_global()
    fig.colorbar(pc, label="Temperature")
    image
  28. moved this from 📚 Backlog to ✅ Done in UXarray Developmenton Jul 17, 2024
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

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions