Matplotlib 3.0 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

The following code blocks plot two bar graphs for men and women. On the y axis, the average salary is plotted, and on the x axis, various groups are plotted within the men and women categories. So, we have a numeric variable on the y axis and a categorical variable on the x axis.

The following code block uses default settings for ticks and ticklabels on the y axis, but uses custom settings for the x axis:

  1. Set up the data and plot bars for the men's data:
menMue = [3, 10, 100, 500, 50]
menSigma = [0.75, 2.5, 25, 125, 12.5]

fig, ax = plt.subplots()
ind = np.arange(len(menMue)) # the x locations for the groups
width = 0.35 # the width of the bars
p1 = ax.bar(ind, menMue, width, color='lightblue', bottom=0,
yerr=menSigma)
  1. Set up the data and plot bars for the women's data:
womenMue = [1000, 3, 30, 800, 1]
womenSigma = [250, 0.75, 8, 200, 0.25]
p2 = ax.bar(ind + width, womenMue, width, color='orange', bottom=0,
yerr=womenSigma)
  1. Set the title, labels, and legend for the figure:
ax.set_title('Scores by group and gender')
ax.set(xticks=(ind + width / 2), xticklabels=('C1', 'C2', 'C3',
'C4', 'C5'), yscale='log')
ax.legend((p1[1], p2[1]), ('Men', 'Women'), bbox_to_anchor=(1.3,1))
  1. Display the figure on the screen:
plt.show()