【问题标题】:matplotlib get colorbar mappable from an axismatplotlib 获取可从轴映射的颜色条
【发布时间】:2021-08-05 02:34:42
【问题描述】:

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

我想做这样的事情:

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()

编辑

可能重复的答案可以部分解决我的问题,如代码 sn-p 中给出的。然而,这个问题更多是关于从轴中检索一般可映射对象,这在 Diziet Asahi 看来似乎是不可能的。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

获取可映射的方式取决于您在 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)

【讨论】:

  • 嗯...毕竟没有统一的方式来引用可映射对象。那么我认为这不是一个好的方向。我应该尽量避免以这种方式制作情节。
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
相关资源
最近更新 更多