【问题标题】:Position colorbar inside figure将颜色条定位在图中
【发布时间】: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=1scatter 中,会出现刻度。
  • 好吧,我可以忽略它,但我宁愿不要。当你运行代码时看起来很糟糕,警告开始飞到你的脸上,必须有更好的方法来做到这一点。 vmin=0, vmax=1 的事情奏效了,所以我把这部分排除在外,谢谢!
  • 好吧,警告就是:tight_layout 只处理缩小和放大子图。如果您的轴不是子图,它将发出警告。您希望拥有不是子图的轴(颜色条)。您基本上有 3 个选项:a) 捕获该特定警告并将其静音,b) 关闭警告,c) 不要使用 tight_layout,而是使用 subplots_adjust。 (tight_layout 只是自动计算subplots_adjust 的输入。)希望对您有所帮助!

标签: python matplotlib color-mapping


【解决方案1】:

可以使用mpl_toolkits.axes_grid1.inset_locator.inset_axes 将一个轴放置在另一个轴内。此轴可用于托管颜色条。它的位置是相对于父轴的,类似于放置图例的方式,使用loc 参数(例如loc=3 表示左下角)。它的宽度和高度可以用绝对数字(英寸)或相对于父坐标轴(百分比)来指定。

cbaxes = inset_axes(ax1, width="30%", height="3%", loc=3) 

import matplotlib.pyplot as plt 
import numpy as np
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

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)

fig.tight_layout()

cbaxes = inset_axes(ax1, width="30%", height="3%", loc=3) 
plt.colorbar(cax=cbaxes, ticks=[0.,1], orientation='horizontal')


plt.show()

请注意,为了抑制警告,可以在添加插入轴之前简单地调用tight_layout

【讨论】:

  • 除了使用loc定位轴方便而不是手动选择坐标(确实很方便)之外,比使用fig.add_axes()还有什么其他优势吗?
  • 不,不必担心坐标的优势。在这个简单的情况下,它可能不太明显,但在一般情况下,您甚至可能不知道使用add_axes 放置轴所需的坐标,而inset_axes 确保轴在其他轴内并相对于它定位。
猜你喜欢
  • 2012-10-29
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
相关资源
最近更新 更多