【发布时间】:2013-08-15 05:44:00
【问题描述】:
我有一个简单的散点图,其中每个点的颜色由 0 到 1 之间的值给出,并设置为所选的颜色图。这是我的代码的MWE:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
x = np.random.randn(60)
y = np.random.randn(60)
z = [np.random.random() for _ in range(60)]
fig = plt.figure()
gs = gridspec.GridSpec(1, 2)
ax0 = plt.subplot(gs[0, 0])
plt.scatter(x, y, s=20)
ax1 = plt.subplot(gs[0, 1])
cm = plt.cm.get_cmap('RdYlBu_r')
plt.scatter(x, y, s=20 ,c=z, cmap=cm)
cbaxes = fig.add_axes([0.6, 0.12, 0.1, 0.02])
plt.colorbar(cax=cbaxes, ticks=[0.,1], orientation='horizontal')
fig.tight_layout()
plt.show()
看起来像这样:
这里的问题是我希望小水平颜色条位置在图的左下角,但使用cax 参数不仅感觉有点hacky,它显然与tight_layout 冲突,导致警告:
/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py:1533: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.
warnings.warn("This figure includes Axes that are not "
难道没有更好的方法来定位颜色条,即当您运行代码时不会收到讨厌的警告?
编辑
我希望颜色条只显示最大值和最小值,即:0 和 1,Joe 帮助我做到这一点,将 vmin=0, vmax=1 添加到 scatter,如下所示:
plt.scatter(x, y, s=20, vmin=0, vmax=1)
所以我要删除这部分问题。
【问题讨论】:
-
每当您手动添加轴时,关于轴不兼容的警告都是正确的。您可以放心地忽略它,只需注意
tight_layout不会考虑颜色条的位置。对于第二个问题,这实际上是因为你的颜色条的最小值和最大值并不完全在 0 和 1 处。(scatter等人,默认情况下将其设置为数据的确切最小值和最大值)如果你通过在vmin=0, vmax=1到scatter中,会出现刻度。 -
好吧,我可以忽略它,但我宁愿不要。当你运行代码时看起来很糟糕,警告开始飞到你的脸上,必须有更好的方法来做到这一点。
vmin=0, vmax=1的事情奏效了,所以我把这部分排除在外,谢谢! -
好吧,警告就是:
tight_layout只处理缩小和放大子图。如果您的轴不是子图,它将发出警告。您希望拥有不是子图的轴(颜色条)。您基本上有 3 个选项:a) 捕获该特定警告并将其静音,b) 关闭警告,c) 不要使用tight_layout,而是使用subplots_adjust。 (tight_layout只是自动计算subplots_adjust的输入。)希望对您有所帮助!
标签: python matplotlib color-mapping