matplotlib从轴

时间:2018-01-06 19:46:32

标签: python matplotlib

我想添加一个颜色条,不包括轴在绘制内容时返回的内容。 有时我会在函数内部绘制一个轴,它不会返回任何内容。 有没有办法从预先完成绘图的轴获取颜色条的可映射? 我相信有足够的关于色谱图和颜色范围的信息绑定到轴本身。

我喜欢这样做:

def plot_something(ax):
    ax.plot( np.random.random(10), np.random.random(10), c= np.random.random(10))

fig, axs = plt.subplots(2)
plot_something(axs[0])
plot_something(axs[1])

mappable = axs[0].get_mappable() # a hypothetical method I want to have.

fig.colorbar(mappable)
plt.show()

修改

可能重复的答案可以部分解决我在代码片段中给出的问题。但是,这个问题更多的是从轴上检索一般的可映射对象,根据Diziet Asahi,这似乎是不可能的。

1 个答案:

答案 0 :(得分:3)

获取可映射的方式取决于您在plot_something()函数中使用的绘图函数。

例如:

  • plot()会返回Line2D个对象。对该对象的引用是 存储在Axes对象的列表ax.lines中。话虽这么说,我不认为Line2D可用作colorbar()的映射
  • scatter()返回PathCollection个集合对象。此对象存储在Axes对象的ax.collections列表中。
  • 另一方面,imshow()会返回一个AxesImage对象,该对象存储在ax.images

您可能必须尝试查看这些不同的列表,直到找到要使用的适当对象。

def plot_something(ax):
    x = np.random.random(size=(10,))
    y = np.random.random(size=(10,))
    c = np.random.random(size=(10,))
    ax.scatter(x,y,c=c)

fig, ax = plt.subplots()
plot_something(ax)
mappable = ax.collections[0]
fig.colorbar(mappable=mappable)