Reputation: 181
I have a two-dimensional list that looks like this.
list_of_Tots:
[[335.06825999999904,
754.4677800000005,
108.76719000000037,
26.491620000000104,
156.56571000000028],
[332.8958600000008,
613.4729919999997,
142.58723599999996,
48.48214800000058,
171.39861200000016],
........
[1388.2799999999681,
670.0599999999969,
1144.8699999999897,
346.81999999999715,
70.37000000000008]]
This two-dimensional list has 10 lists in it and each list has 5 numbers.
I want to display bar charts of each list by using matplotlib on Jupyter notebook so implemented the code below.
def bar_chart(y_list, x_list=['L','LC','C','RC','R']):
x = np.array(x_list)
y = np.array(y_list)
plt.ylabel('Bedload[kg/m/year]')
plt.bar(x, y)
def display_bar_charts(list_of_arraies):
num_of_tots = len(list_of_arraies)
%matplotlib inline
fig = plt.figure(figsize=(3*5, 6))
for i, y_list in enumerate(list_of_arraies):
bar_chart(y_list)
ax = plt.subplot(2, 5, i+1)
ax.set_title('Tot({})'.format(i+1))
fig.tight_layout()
display_bar_charts(list_of_Tots)
and then I got a result like this
I intended to display 10 figures because 'list_of_Tots' has 10 lists in it but there are only 9 figures on the image. I looked into the data and it turned out that the first list in 'list_of_Tots' doesn't exist on the image and the second list was on the first place where the first list was supposed to be on. And the third list is on the second place..., the forth list is on the third place....and at the last place, there's no bars in it.
Could you please find some mistakes in this code? Thank you.
Upvotes: 0
Views: 21
Reputation: 756
As mentioned in the comment, you need to create some axes before you plot something within it. So do that and pass the axes to your bar plotting function:
def bar_chart(ax, y_list, x_list=['L','LC','C','RC','R']):
x = np.array(x_list)
y = np.array(y_list)
ax.set_ylabel('Bedload[kg/m/year]')
ax.bar(x, y)
def display_bar_charts(list_of_arraies):
num_of_tots = len(list_of_arraies)
%matplotlib inline
fig = plt.figure(figsize=(3*5, 6))
for i, y_list in enumerate(list_of_arraies):
ax = plt.subplot(2, 5, i+1)
bar_chart(ax, y_list)
ax.set_title('Tot({})'.format(i+1))
fig.tight_layout()
Otherwise plt.bar
will look for the last active axes, which do not exist in your loop for i=0
, since bar_chart
is called before the axes are created.
Upvotes: 1