Reputation: 1925
I want to iterate over lists and plot a boxplot of each list. Because the data can not fit all into memory, I can't assign a pre-defined number of boxplots to draw, so I'm using the subplot function to add plots iteratively.
My problem is that the axis labels are not being added to the plot with the boxplot, and only the last label is shown. How is it possible to label boxplots iteratively with subplot.
A simplified example of what I want to do is below. Although in reality I'm actually recycling the same list in a loop rather than iterating over a list of lists, but it serves to illustrate the problem. As it can be seen only 'lb' is set in the yaxis and the plot is not showing 'la' for the first bottom boxplot,
Thanks.
%matplotlib inline
import matplotlib.pyplot as plt
la = [24, 28, 31, 34, 38, 40, 41, 42, 43, 44]
lb = [5, 8, 10, 12, 15, 18, 21, 25, 30, 39]
names = ['la', 'lb']
myList = [la] + [lb]
myList
# set fig for boxplots
fig, ax = plt.subplots(sharex=True)
# Add a horizontal grid to the plot
ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
ax.set_axisbelow(True)
ax.set_title('Some Title')
for i,l in enumerate(myList):
ax.boxplot(l, vert=False, positions = [i])
ax.set_yticklabels([names[i]])
ax.set_ylim(-0.5, len(myList)-0.5)
Upvotes: 2
Views: 2592
Reputation: 339550
Setting the label inside the loop will overwrite the previous ticklabel. So the labels should be set outside the loop. You also need to make sure that both labels actually have ticks.
A solution is hence to add
ax.set_yticks(range(len(myList)))
ax.set_yticklabels(names)
outside of the loop.
Complete code:
import matplotlib.pyplot as plt
la = [24, 28, 31, 34, 38, 40, 41, 42, 43, 44]
lb = [5, 8, 10, 12, 15, 18, 21, 25, 30, 39]
names = ['la', 'lb']
myList = [la] + [lb]
myList
# set fig for boxplots
fig, ax = plt.subplots(sharex=True)
# Add a horizontal grid to the plot
ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
ax.set_axisbelow(True)
ax.set_title('Some Title')
for i,l in enumerate(myList):
ax.boxplot(l, vert=False, positions = [i])
ax.set_yticks(range(len(myList)))
ax.set_yticklabels(names)
ax.set_ylim(-0.5, len(myList)-0.5)
plt.show()
Upvotes: 2