如何在 python matplotlib 中为 pcolor 设置固定颜色条?

发布于 2024-09-05 03:26:25 字数 779 浏览 0 评论 0原文

我使用 pcolor 和自定义颜色图来绘制值矩阵。我设置了颜色图,使低值是白色,高值是红色,如下所示。我所有矩阵的值都在 0 到 20(含)之间,我希望 20 始终为纯红色,0 始终为纯白色,即使矩阵的值不跨越整个范围。例如,如果我的矩阵只有 2 到 7 之间的值,我不希望它将 2 绘制为白色,将 7 绘制为红色,而是将其着色,就好像范围仍然是 0 到 20 一样。我该怎么做?我尝试使用 colorbar 的“ticks=”选项,但它不起作用。

这是我当前的代码(假设“my_matrix”包含要绘制的值):

cdict = {'red': ((0.0, 1.0, 1.0),
         (0.5, 1.0, 1.0),
         (1.0, 1.0, 1.0)),
     'green': ((0.0, 1.0, 1.0),
           (0.5, 1.0, 1.0),
           (1.0, 0.0, 0.0)),
     'blue': ((0.0, 1.0, 1.0),
          (0.5, 1.0, 1.0),
          (1.0, 0.0, 0.0))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
colored_matrix = plt.pcolor(my_matrix, cmap=my_cmap)
plt.colorbar(colored_matrix, ticks=[0, 5, 10, 15, 20])

知道如何修复此问题以获得正确的结果吗?非常感谢。

I am using pcolor with a custom color map to plot a matrix of values. I set my color map so that low values are white and high values are red, as shown below. All of my matrices have values between 0 and 20 (inclusive) and I'd like 20 to always be pure red and 0 to always be pure white, even if the matrix has values that don't span the entire range. For example, if my matrix only has values between 2 and 7, I don't want it to plot 2 as white and 7 as red, but rather color it as if the range is still 0 to 20. How can I do this? I tried using the "ticks=" option of colorbar but it did not work.

Here is my current code (assume "my_matrix" contains the values to be plotted):

cdict = {'red': ((0.0, 1.0, 1.0),
         (0.5, 1.0, 1.0),
         (1.0, 1.0, 1.0)),
     'green': ((0.0, 1.0, 1.0),
           (0.5, 1.0, 1.0),
           (1.0, 0.0, 0.0)),
     'blue': ((0.0, 1.0, 1.0),
          (0.5, 1.0, 1.0),
          (1.0, 0.0, 0.0))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
colored_matrix = plt.pcolor(my_matrix, cmap=my_cmap)
plt.colorbar(colored_matrix, ticks=[0, 5, 10, 15, 20])

any idea how I can fix this to get the right result? thanks very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为人所爱 2024-09-12 03:26:25

猜测:你的色彩图可能没问题。绘图时尝试调整vminvmax

pylab.imshow(im, vmin=0, vmax=20)

A guess: Your colormap is probably fine. Try to adjust the vmin and vmax when plotting.

pylab.imshow(im, vmin=0, vmax=20)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文