matplotlib 从轴获取可映射的颜色条

Hos*_*hoi 3 python matplotlib

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

我希望 tp 做这样的事情:

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()
Run Code Online (Sandbox Code Playgroud)

编辑

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

Diz*_*ahi 5

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

例如:

  • plot()返回一个Line2D对象。对该对象的引用存储在ax.linesAxes 对象的列表中。话虽如此,我认为 aLine2D不能用作可映射的colorbar()
  • scatter()返回一个PathCollection集合对象。该对象存储在ax.collectionsAxes 对象的列表中。
  • 另一方面,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)
Run Code Online (Sandbox Code Playgroud)