如何在 python matplotlib 颜色图中提高颜色分辨率

key*_*ert 5 python matlab numpy matplotlib colormap

我正在制作 2D numpy 网格的颜色图:

X, Y = np.meshgrid(fields, frequencies)
cs = ax.contourf(X, Y, fields_freqs_abs_grid, cmap="viridis", N=256)
Run Code Online (Sandbox Code Playgroud)

fields_freqs_abs_grid 中的值按颜色绘制,已经按对数缩放。

python 的 matplotlib 生成的颜色图很粗糙——即使我使用“N=256”作为 RGB 像素数,它也可以缩放超过 8 种颜色。将 N 增加到 2048 没有任何改变。在相同数据上使用 MatLab 语言绘制的绘图会生成具有显着更高颜色分辨率的颜色图。如何增加 Python 中映射的颜色数量?

结果是: 在此处输入图片说明

但我希望结果是: 在此处输入图片说明

谢谢!

Y. *_*Luo 4

Warren Weckesser 的评论绝对有效,并且可以为您提供高分辨率图像。我在下面的例子中实现了他的想法。

关于 use contourf(),我不确定这是否是版本相关的问题,但在最新版本中, contourf()没有 kwarg for N.

正如您在文档中看到的,您希望使用Narg (语法为:)contourf(X,Y,Z,N)来指定要绘制的级别数,而不是 RGB 像素的数量。contourf()绘制填充轮廓,分辨率取决于要绘制的级别数。你N=256什么都不做,contourf()会自动选择7个级别

下面的代码是根据官方例子修改的,比较不同的分辨率N。如果存在版本问题,此代码会给出以下图python 3.5.2; matplotlib 1.5.3

import numpy as np
import matplotlib.pyplot as plt

delta = 0.025

x = y = np.arange(-3.0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
fig.set_size_inches(8, 6)

# Your code sample
CS1 = ax1.contourf(X, Y, Z, cmap="viridis", N=256)
ax1.set_title('Your code sample')
ax1.set_xlabel('word length anomaly')
ax1.set_ylabel('sentence length anomaly')
cbar1 = fig.colorbar(CS1, ax=ax1)

# Contour up to N=7 automatically-chosen levels, 
# which should give the same as your code.
N = 7
CS2 = ax2.contourf(X, Y, Z, N, cmap="viridis")
ax2.set_title('N=7')
ax2.set_xlabel('word length anomaly')
ax2.set_ylabel('sentence length anomaly')
cbar2 = fig.colorbar(CS2, ax=ax2)

# Contour up to N=100 automatically-chosen levels.
# The resolution is still not as high as using imshow().
N = 100
CS3 = ax3.contourf(X, Y, Z, N, cmap="viridis")
ax3.set_title('N=100')
ax3.set_xlabel('word length anomaly')
ax3.set_ylabel('sentence length anomaly')
cbar3 = fig.colorbar(CS3, ax=ax3)

IM = ax4.imshow(Z, cmap="viridis", origin='lower', extent=(-3, 3, -3, 3))
ax4.set_title("Warren Weckesser's idea")
ax4.set_xlabel('word length anomaly')
ax4.set_ylabel('sentence length anomaly')
cbar4 = fig.colorbar(IM, ax=ax4)

fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述