matplotlib 从轴获取可映射的颜色条 [英] matplotlib get colorbar mappable from an axis

查看:30
本文介绍了matplotlib 从轴获取可映射的颜色条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add a colorbar WITHOUT what is returned by the axis on plotting things. Sometimes I draw things to an axis inside a function, which returns nothing. Is there a way to get the mappable for a colorbar from an axis where a plotting has been done beforehand? I believe there is enough information about colormap and color range bound to the axis itself.

我想tp做这样的事情:

I'd like tp do something like this:

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 的说法,这似乎是不可能的.

The answer to the possible duplicate can partly solve my problem as is given in the code snippet. However, this question is more about retrieving a general mappable object from an axis, which seems to be impossible according to Diziet Asahi.

推荐答案

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

The way you could get your mappable would depend on what plotting function your are using in your plot_something() function.

例如:

  • plot()返回 Line2D 对象.对该对象的引用是存储在 Axes 对象的列表 ax.lines 中.话虽如此,我认为 Line2D 不能用作 colorbar()
  • 的可映射对象
  • scatter()返回一个 PathCollection 集合对象.该对象存储在 Axes 对象的 ax.collections 列表中.
  • 另一方面,imshow() 返回一个 AxesImage 对象,该对象存储在 ax.images
  • plot() returns a Line2D object. A reference to that object is stored in the list ax.lines of the Axes object. That being said, I don't think a Line2D can be used as a mappable for colorbar()
  • scatter() returns a PathCollection collection object. This object is stored in the ax.collections list of the Axes object.
  • On the other hand, imshow() returns an AxesImage object, which is stored in ax.images

您可能需要尝试查看这些不同的列表,直到找到要使用的合适对象.

You might have to try and look in those different list until you find an appropriate object to use.

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)

这篇关于matplotlib 从轴获取可映射的颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆