Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all bars in a matplotlib bar chart?

It is easy to retrieve all lines in a line chart by calling the get_lines() function. I cannot seem to find an equivalent function for a barchart, that is retrieving all Rectangle instances in the AxesSubplot. Suggestions?

like image 714
Jimmy C Avatar asked Mar 27 '14 13:03

Jimmy C


People also ask

How do I show bar values in Matplotlib?

Call matplotlib. pyplot. barh(x, height) with x as a list of bar names and height as a list of bar values to create a bar chart. Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable.


1 Answers

Another option that might be useful to some people is to access ax.containers. You have to be a little careful though as if your plot contains other types of containers you'll get those back too. To get just the bar containers something like

from matplotlib.container import BarContainer
bars = [i for i in ax.containers if isinstance(i, BarContainer)]

This can be pretty powerful with a few tricks (taking inspiration from the accepted example).

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(2, 5)

ax.bar(x, y[0], width=0.5)
ax.bar(x + 0.5, y[1], width=0.5)

for bar, color in zip(ax.containers, ("red", "green")):
    # plt.setp sets a property on all elements of the container
    plt.setp(bar, color=color)

will give you:

enter image description here

If you add some labels to your plots you can construct a dictionary of containers to access them by label

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(2, 5)

ax.bar(x, y[0], width=0.5)
ax.bar(x + 0.5, y[1], width=0.5, label='my bars')

named_bars = {i.get_label(): i for i in ax.containers}
plt.setp(named_bars["my bars"], color="magenta")

will give you

enter image description here

Of course, you can still access an individual bar patch within a container e.g.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(2, 5)

ax.bar(x, y[0], width=0.5)
ax.bar(x + 0.5, y[1], width=0.5)

plt.setp(ax.containers[0], color="black")
plt.setp(ax.containers[1], color="grey")
ax.containers[0][3].set_color("red")

enter image description here

like image 176
tomjn Avatar answered Sep 19 '22 16:09

tomjn