How to remove/omit smaller contour lines using matplotlib

前端 未结 2 1029
暗喜
暗喜 2020-12-06 03:31

I am trying to plot contour lines of pressure level. I am using a netCDF file which contain the higher resolution data (ranges from 3 km to 27 km). Due to highe

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 04:00

    This is a pretty bad solution, but it's the only one that I've come up with. Use the get_contour_verts function in this solution you linked to, possibly with the matplotlib._cntr module so that nothing gets plotted initially. That gives you a list of contour lines, sections, vertices, etc. Then you have to go through that list and pop the contours you don't want. You could do this by calculating a minimum diameter, for example; if the max distance between points is less than some cutoff, throw it out.

    That leaves you with a list of LineCollection objects. Now if you make a Figure and Axes instance, you can use Axes.add_collection to add all of the LineCollections in the list.

    I checked this out really quick, but it seemed to work. I'll come back with a minimum working example if I get a chance. Hope it helps!


    Edit: Here's an MWE of the basic idea. I wasn't familiar with plt._cntr.Cntr, so I ended up using plt.contour to get the initial contour object. As a result, you end up making two figures; you just have to close the first one. You can replace checkDiameter with whatever function works. I think you could turn the line segments into a Polygon and calculate areas, but you'd have to figure that out on your own. Let me know if you run into problems with this code, but it at least works for me.

    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    def checkDiameter(seg, tol=.3):
        # Function for screening line segments. NB: Not actually a proper diameter.
        diam = (seg[:,0].max() - seg[:,0].min(),
                seg[:,1].max() - seg[:,1].min())
        return not (diam[0] < tol or diam[1] < tol)
    
    # Create testing data
    x = np.linspace(-1,1, 21)
    xx, yy = np.meshgrid(x,x)
    z = np.exp(-(xx**2 + .5*yy**2))
    
    # Original plot with plt.contour
    fig0, ax0 = plt.subplots()
    # Make sure this contour object actually has a tiny contour to remove
    cntrObj = ax0.contour(xx,yy,z, levels=[.2,.4,.6,.8,.9,.95,.99,.999])
    
    # Primary loop: Copy contours into a new LineCollection
    lineNew = list()
    for lineOriginal in cntrObj.collections:
        # Get properties of the original LineCollection
        segments = lineOriginal.get_segments()
        propDict = lineOriginal.properties()
        propDict = {key: value for (key,value) in propDict.items()
            if key in ['linewidth','color','linestyle']}  # Whatever parameters you want to carry over
        # Filter out the lines with small diameters
        segments = [seg for seg in segments if checkDiameter(seg)]
        # Create new LineCollection out of the OK segments
        if len(segments) > 0:
            lineNew.append(mpl.collections.LineCollection(segments, **propDict))
    
    # Make new plot with only these line collections; display results
    fig1, ax1 = plt.subplots()
    ax1.set_xlim(ax0.get_xlim())
    ax1.set_ylim(ax0.get_ylim())
    for line in lineNew:
        ax1.add_collection(line)
    plt.show()
    

    FYI: The bit with propDict is just to automate bringing over some of the line properties from the original plot. You can't use the whole dictionary at once, though. First, it contains the old plot's line segments, but you can just swap those for the new ones. But second, it appears to contain a number of parameters that are in conflict with each other: multiple linewidths, facecolors, etc. The {key for key in propDict if I want key} workaround is my way to bypass that, but I'm sure someone else can do it more cleanly.

提交回复
热议问题