python - 如何在 python matplotlib colormap 中增加颜色分辨率

标签 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)

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

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

结果是:enter image description here

但我希望结果是:enter image description here

谢谢!

最佳答案

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

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

正如您在文档中看到的,您希望使用 N 作为参数(语法:contourf(X,Y,Z,N))来指定您要绘制多少级别而不是 RGB 像素的数量。 contourf() 绘制填充轮廓,分辨率取决于要绘制的层数。您的 N=256 不会做任何事情,contourf() 会自动选择 7 levels .

以下代码修改自官方example , 比较具有不同 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()

enter image description here

关于python - 如何在 python matplotlib colormap 中增加颜色分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44836348/

相关文章:

python - netcat 发送额外的 "X"UDP 数据包

matlab - 选择一列中的值与特定向量匹配的行

matlab - 如何编写 protected MATLAB 脚本/程序?

python - 用 n 表示具有整数 A i,j := sin(z i, j) 的 nxn 数组,其中 zi, j 是 (0,2pi] 中均匀分布的随机数

python - numpy,重新排列 : Methods to convert a list of dict's to a np. 重新排列?

python - 使用 python 将数据嵌入到二进制图像中

python - 编写自学音乐制作程序

python - 如果循环更新其自身之外的内容 - 如何构建等效的或 lambda/列表理解?

matlab - 在字符串数组中查找重复的条目?

python - 在 x 和 y 坐标的 numpy 数组中查找最近点的索引