How does one retrieve data programmatically from a matplotlib bar chart? I can do it for a matplotlib line chart as follows, so maybe I’m fairly close:
JavaScript
x
10
10
1
import matplotlib.pyplot as plt
2
3
plt.plot([1,2,3],[4,5,6])
4
5
axis = plt.gca()
6
line = axis.lines[0]
7
x_plot, y_plot = line.get_xydata().T
8
print("x_plot: ", x_plot)
9
print("y_plot: ", y_plot)
10
for a bar chart, however, there are no lines, and I’m unclear what the equivalent object is:
JavaScript
1
4
1
plt.bar([1,2,3], [4,5,6])
2
axis = plt.gca()
3
???
4
FWIW, here are a couple of related postings (that don’t go into bar charts):
Advertisement
Answer
- The API for
matplotlib.pyplot.bar
returns aBarContainer
objectmatplotlib.patches.Rectangle
provides a full accounting of thePatch
methods.- This object is iterable, and the various location components can be extracted with the appropriate methods, as shown below.
JavaScript
1
17
17
1
import matplotlib.pyplot as plt
2
3
rects = plt.bar([1,2,3], [4,5,6])
4
5
for rect in rects:
6
print(rect)
7
xy = rect.get_xy()
8
x = rect.get_x()
9
y = rect.get_y()
10
height = rect.get_height()
11
width = rect.get_width()
12
13
[out]:
14
Rectangle(xy=(0.6, 0), width=0.8, height=4, angle=0)
15
Rectangle(xy=(1.6, 0), width=0.8, height=5, angle=0)
16
Rectangle(xy=(2.6, 0), width=0.8, height=6, angle=0)
17