Matplotlib标准化颜色条(Python) [英] Matplotlib normalize colorbar (Python)
问题描述
我正在尝试使用matplotlib(当然还有numpy)绘制轮廓线图.它可以正常工作,可以绘制应绘制的图,但是很遗憾,我无法设置颜色栏范围.问题是我有很多图,需要所有图都具有相同的颜色条(相同的最小和最大值,相同的颜色).我复制并粘贴了我在互联网上找到的几乎所有代码段,但均未成功.到目前为止,我的代码:
I'm trying to plot a contourf-plot using matplotlib (and numpy of course). And it works, it plots what it should plot, but unfortunatelly I cannot set the colorbar range. The problem is that I have a plenty of plots and need all of them to have the same colorbar (same min and max, same colors). I copy&past-ed almost every code snippet I found on the internet, but without success. My code so far:
import numpy as np;
import matplotlib as mpl;
import matplotlib.pyplot as plt;
[...]
plotFreq, plotCoord = np.meshgrid(plotFreqVect, plotCoordVect);
figHandler = plt.figure();
cont_PSD = plt.contourf(plotFreq, plotCoord, plotPxx, 200, linestyle=None);
normi = mpl.colors.Normalize(vmin=-80, vmax=20);
colbar_PSD = plt.colorbar(cont_PSD);
colbar_PSD.set_norm(normi);
#colbar_PSD.norm = normi;
#mpl.colors.Normalize(vmin=-80, vmax=20);
plt.axis([1, 1000, -400, 400]);
如您所见,colorbar规范有三行不同,它们都不起作用.范围仍然是自动设置的...我的意思是其他所有东西都在起作用,为什么不显示颜色栏?我什至没有收到错误或警告.
As you can see there are three different lines for the colorbar norm, none of them is working. The range is still set automatically... I mean everything else is working, why not the colorbar? I don't even get errors or warnings.
谢谢,itpdg
图片,带有plt.clim(-80,20):
EDIT 1: Pictures, with plt.clim(-80,20):
推荐答案
I ran into this issue a while back and thought it was a bug (see MPL issue #5055). It's not, but it does require using the extend
kwarg, which was non-intuitive to me. Here's what you want to do:
normi = mpl.colors.Normalize(vmin=-80, vmax=20)
cont_PSD = plt.contourf(plotFreq, plotCoord, plotPxx,
np.linspace(-80, 20, 200),
linestyle=None,
norm=normi, extend='both')
plt.colorbar(colbar_PSD)
您可以取消 plt.clim
, colbar_PSD.set_norm
和其他类似调用.
You can do-away with the plt.clim
, colbar_PSD.set_norm
and other similar calls.
在此处,可以找到有关 extend =
的更多示例用法.
More examples uses of extend=
are available here.
请注意,这将创建一个在顶部和底部带有三角形"的颜色条,表明数据超出了颜色条,但是我认为一旦习惯了它们,它们就会具有描述性.
Note that this will create a colorbar with 'triangles' at the top and bottom indicating that the data extends beyond the colorbar, but I think you'll like them once you get used to them, they are descriptive.
祝你好运!
这篇关于Matplotlib标准化颜色条(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!