Search code examples
pythonmatplotlibcontourf

Contourf produces color Swatches


I would like to have interpolated values (gradients) between the data shown below:

DataPoints

However, the result I get is this:

enter image description here

fig, (ax1) = plt.subplots(figsize=(12,6))
colors = plt.cm.get_cmap('autumn_r')
ax1.set_facecolor("gray")
levels,steps = np.linspace(min(monet_mag),max(monet_mag),graphlevels,retstep=True)
ticks = np.linspace(max(monet_mag),min(monet_mag),10) 
xgrid = np.linspace(min(monet_lpa), max(monet_lpa),145)
ygrid = np.linspace(min(monet_decpa), max(monet_decpa),145)
xgrid, ygrid = np.meshgrid(xgrid, ygrid,indexing='xy')
interpolated_grid = griddata((monet_lpa,monet_decpa),monet_mag, (xgrid, ygrid), method='linear')
cax = ax1.contourf(monet_lpa, monet_decpa, interpolated_grid, levels=levels, cmap=colors,extend="both")

Note that in the position of gridsize for griddata I have explicitly put "145". This is dimension of all the lists. If I change the gridsize (to 300) I get an error of:

TypeError(f"Length of x ({nx}) must match number of "
TypeError: Length of x (145) must match number of columns in z (300).

But changing gridsize doesn't have anything to do with the "z" axis (monet_mag).

Please let me know if there is something obvious I am doing wrong.


Solution

  • interpolated_grid is a [145, 145] array of z values. When you plot those z values with contourf you need to pass x and y coordinates for those interpolated values, and instead you are passing the x and y coordinates of the input data. You want to pass the x and y coordinates of the grid instead (ie: xgrid and ygrid).

    This is also causing the error when you change the gridsize.

    So

    cax = ax1.contourf(xgrid, ygrid, interpolated_grid, levels=levels, cmap=colors,extend="both"
    

    Should work and allow you to set the gridsize to whatever you wish.

    I believe that contourf can also handle interpolation - so

    cax = ax1.contourf(monet_lpa, monet_decpa, monet_mag, levels=levels, cmap=colors,extend="both")
    

    Should also get you a sensible result.