Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to smoothen 2D color map in matplotlib

My question is if there is any way to smoothen 2D color map using matplotlib? My code:

def map():
    # setup parameters
    j = 0
    N = 719
    N2 = 35
    x = np.linspace(190, 800, N) 
    y = np.linspace(10, 360, N2) # (1,2,3), 1 - start Temp, 2- end temp + 10K, 3 - how many steps to reach it
    z = []
    A = np.zeros([35,719]) # [1 2], 1 - number of spectras, 2 - delta wavelength
    # run
    for i in range(10,360,10):
            Z = []
            file_no = (str(0) + str(i))[-3:]
            data = np.genfromtxt('C:\\Users\\micha_000\\Desktop\\Measure\\' + '160317_LaPONd_g500_%s_radio.txt'%file_no,skip_header = 12)
            for line in data:
                Z.append(line[1]-6000)
            A[j,:] = Z
            j = j+1
    X, Y = np.meshgrid(x,y)
    fig, ax = plt.subplots()
    cs = ax.contourf(X, Y, A, cmap=cm.viridis)
    norm = colors.Normalize(vmin = 0, vmax = 1)
    plt.xlabel('wavelength [nm]')
    plt.ylabel('temperature [K]')
    plt.title('LaPONd_g500')
    cbar = fig.colorbar(cs, norm = norm)
    plt.savefig('C:\\Users\\micha_000\\Desktop\\Measure\\LaPONd_g500_radio_map.png')
    plt.show()
    plt.close()

And here is an example of what i receive: enter image description here

Is there any way to make it look better by smoothening pixels transitions?

like image 923
Maq92 Avatar asked Oct 26 '25 03:10

Maq92


1 Answers

The problem is not the palette (which are all smooth in matplotlib), but that fact that you are using contourf(), which generates a finite set of countours, each with a single color, and is therefore not smooth. The default is something like 10 countours.

One quick solution:, increase the number of contour levels by specifying levels (you can also give an array of which levels to include):

cs = ax.contourf(X, Y, A, cmap=cm.viridis, levels=100)

Better yet, since it seems your data data is already on a grid (e.g. X,Y,Z values for each pixel), you should use pcolormesh(X,Y,A) instead of contour to plot it. That will plot with fully continuous values, rather than steps.

like image 114
kosack Avatar answered Oct 27 '25 18:10

kosack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!