Search code examples
pythonmatplotlibcontourmesh

Making a meshgrid of a non-uniform coordinates


I'm trying to plot the contours of a multivariate function evaluated at non-uniform coordinates. The problem arises from having the coordinates stored as a 1D array, specifically two columns of shape (n,). When I scatter the x and y values I get the desired domain

enter image description here

Unfortunately, contourf cannot plot 1D arrays. Therefore, I have tried using tricontourf, which can handle 1D arrays. However, for some reason, the contour plot exceeds the domain

enter image description here

I tried to create a mesh grid and reshape the z(x, y) values so that I could use the regular contourf function. However, the resulting mesh grid does not appear as expected

enter image description here

Masking the additional region would solve the problem, but I'm not sure how to do that.


Solution

  • Since your edges appear to be straight lines, you should be able to define masks that block out the region you don't want to be inside the contour. This process is nearly identical to what is explained in this answer.

    I had to generate the domain because you didn't provide those details, but once generated you can do this:

    import matplotlib.pyplot as plt
    import matplotlib.tri as tri
    
    # define x and y here
    
    z = x**2 + y**2
    
    triang = tri.Triangulation(x, y)
    x2 = x[triang.triangles].mean(axis=1) 
    y2 = y[triang.triangles].mean(axis=1)
    cond1 = (x2 > 0.6)&(y2 < 1)
    cond2 = (y2 - 2.5*(x2 - 0.6) < 0)
    triang.set_mask(cond1&cond2)
    
    
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,5))
    ax1.scatter(x, y)
    ax2.tricontourf(triang, z)
    ax2.set_xlim(ax1.get_xlim())
    ax2.set_ylim(ax1.get_ylim())
    fig.tight_layout()
    fig.show()
    

    Results: