如何实现与 matplotlib.pyplot.imshow 函数一起使用的循环插值方法?
当imshow函数用于可视化具有周期性的数据时,例如24小时时钟的时间,循环颜色图非常有用。但是,如果使用 imshow 使用插值来放大数据,则绘图不会按预期显示。
见下图:
import numpy as np
import matplotlib.pyplot as plt
colormap = plt.cm.twilight_shifted
# Create an array with values between 0-3
arr = np.random.randint(0,4,size=[16,16])
# Create a smaller array with values between 20-23
patch = np.random.randint(20,24,size=[4,4])
# Insert the patch in the middle of the array
arr[6:10,6:10] = patch
# Visualize the array, without interpolation
plt.figure(figsize=[18,10])
plt.imshow(arr, cmap = colormap, aspect='auto', interpolation=None)
plt.colorbar()
# Visualize the array, with interpolation
plt.figure(figsize=[18,10])
plt.imshow(arr, cmap = colormap, aspect='auto', interpolation='bicubic')
plt.colorbar()
产生两个图:
您可以看到插值在两组值之间创建了一条白线,对应于 12 左右的值。但是,由于我们使用的是循环颜色图,所以我实际上期望在 [0,3] 和 [0,3] 之间插值的值[20,23] 群体为黑人。我认为这是因为 imshow 函数中实现的插值方法没有考虑颜色图的循环性。
关于如何实现适当的可视化插值有什么想法吗?循环颜色图的循环插值是否应该作为一项功能添加到 matplotlib 中?
一个很好的解决方法是使用
interpolation_stage='rgba'
。设置该属性后,将在计算颜色之后完成插值。我认为这没有任何缺点,除非你的颜色图有急剧的跳跃。
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.htm
import numpy as np
import matplotlib.pyplot as plt
colormap = plt.cm.twilight_shifted
X, Y = np.meshgrid(np.arange(16), np.arange(16))
arr = X % 8
fig, axes = plt.subplots(figsize=[30,10], dpi=300, ncols=3)
# no interpolation
axes[0].imshow(arr, cmap = colormap, aspect='auto', interpolation=None)
axes[0].set_title('No interpolation')
# bicubic
axes[1].imshow(arr, cmap=colormap, aspect='auto',
interpolation='bicubic'
)
axes[1].set_title('Bicubic interpolation')
# bicubic with color interpolation
ax_img = axes[2].imshow(arr, cmap=colormap, aspect='auto',
interpolation='bicubic', interpolation_stage='rgba'
)
axes[2].set_title('Bicubic color interpolation')
plt.colorbar(mappable=ax_img, ax=axes[2])