Search code examples
pythonpandasmatplotlibplotbar-chart

How to get a BarContainer Object from an AxesSubplot object in matplotllib?


I'm fairly new with matplotlib, but as I understand:

fig,ax = plt.subplot()
ax.bar(x,y) 

or

bar = ax.bar(x,y)

returns a BarContainer type object. From this we can bar.axes to get the axes ax on which this is plotted.

but what if we have an axes ax and we didn't explicitly store the barplot in a bar object. Now we go ahead and do a whole lot of changes on the axes ax, as in ax.position ax.legend etc etc. Now we have an AxesSubplot type object ax....from this, how can we extract our BarContainer type object?

I have a function that accepts the subscriptable BarContainer object, and by the end of my processing I only have an AxesSubplot type object... I can't figure out how to get one from the other.. We can get artists, labels, axis etc etc from the AxesSubplot object but I see no way to get the Container type object from it. Please assist, Thanks!


Solution

  • You can get a list of all containers in the axes by using ax.containers

    fig, ax = plt.subplots()
    ax.bar(x, y) 
    
    con = ax.containers
    print(con)
    # [<BarContainer object of 3 artists>]