如何在 matplotlib 中平滑 2D 颜色图

How to smoothen 2D color map in matplotlib

我的问题是是否有任何方法可以使用 matplotlib 平滑 2D 彩色地图?我的代码:

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()

这是我收到的一个例子:

有什么方法可以通过平滑像素过渡使其看起来更好吗?

将 png 作为数组打开,并使用均值过滤器对其进行模糊处理。搜索卷积过滤器以了解更多信息。我刚刚使用了一个 25 像素的方形平均滤波器,但你可以使用高斯分布使其看起来更平滑..

import numpy as np
from scipy import ndimage, signal, misc

img = ndimage.imread('C:/.../Zrj50.png')

#I used msPaint to get coords... there's probably a better way
x0, y0, x1, y1 = 87,215,764,1270 #chart area (pixel coords)

#you could use a gaussian filter to get a rounder blur pattern
kernel = np.ones((5,5),)/25 #mean value convolution

#convolve roi with averaging filter
#red
img[x0:x1, y0:y1, 0] = signal.convolve2d(img[x0:x1, y0:y1, 0], kernel, mode='same', boundary='symm')
#green
img[x0:x1, y0:y1, 1] = signal.convolve2d(img[x0:x1, y0:y1, 1], kernel, mode='same', boundary='symm')
#blue
img[x0:x1, y0:y1, 2] = signal.convolve2d(img[x0:x1, y0:y1, 2], kernel, mode='same', boundary='symm')

#do it again for ledgend area
#...

misc.imsave('C:/.../Zrj50_blurred.png', img)

改用高斯非常简单:

#red
img[x0:x1, y0:y1, 0] = ndimage.gaussian_filter(img[x0:x1, y0:y1, 0], 4, mode='nearest')

问题不在于调色板(它们在 matplotlib 中都很平滑),而是您正在使用 contourf() 的事实,它会生成一组有限的计数,每个计数都有一种颜色,因此不光滑。默认值类似于 10 个计数。

一个快速解决方案:通过指定级别来增加等高线级别的数量(您也可以给出要包含哪些级别的数组):

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

更好的是,因为您的数据数据似乎已经在网格上(例如每个像素的 X、Y、Z 值),您应该使用 pcolormesh(X,Y,A) 而不是等高线来绘制它。这将绘制完全连续的值,而不是步骤。