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

How to do it...

The following code draws a bar plot:

  1. Set up data for the x and y axes:
month_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
units_sold = [500, 600, 750, 900, 1100, 1050, 1000, 950, 800, 700,
550, 450]
  1. Allocate the space and specify the layout of the figure:
fig, ax = plt.subplots()
  1. Set the descriptive month names as x axis ticks:
plt.xticks(month_num, calendar.month_name[1:13], rotation=20)
  1. Plot the bar graph:
plot = ax.bar(month_num, units_sold)
  1. Add the data value to the head of the bar:
for rect in plot:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.002*height,'%d' %
int(height), ha='center', va='bottom')
  1. Display the graph on the screen:
plt.show()