如何在 python matplotlib 中为 pcolor 设置固定颜色条?
我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
猜测:你的色彩图可能没问题。绘图时尝试调整
vmin
和vmax
。A guess: Your colormap is probably fine. Try to adjust the
vmin
andvmax
when plotting.