matplotlib 从轴获取可映射的颜色条 [英] matplotlib get colorbar mappable from an axis
问题描述
我想添加一个颜色条,而没有轴在绘制事物时返回的内容.有时我将事物绘制到函数内的轴上,该轴不返回任何内容.有没有一种方法可以从预先完成绘制的轴上获取颜色条的可映射对象?我相信有足够的关于绑定到轴本身的颜色图和颜色范围的信息.
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 aLine2D
object. A reference to that object is stored in the listax.lines
of the Axes object. That being said, I don't think aLine2D
can be used as a mappable forcolorbar()
scatter()
returns aPathCollection
collection object. This object is stored in theax.collections
list of the Axes object.- On the other hand,
imshow()
returns anAxesImage
object, which is stored inax.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屋!