Reputation: 1097
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.
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()
EDIT
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.
Upvotes: 6
Views: 6625
Reputation: 40667
The way you could get your mappable would depend on what plotting function your are using in your plot_something()
function.
for example:
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.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)
Upvotes: 8