上QQ阅读APP看书,第一时间看更新
How it works...
Here is the explanation of the preceding code blocks:
- Older versions of Matplotlib accept only floating-point data types as their arguments for data. So, the months have to be represented in a numerical format.
- month_num and units_sold are Python lists representing the number of units sold in each month of a year.
- plt.subplots() allows us to define the layout of the figure in terms of the number of graphs and how they should be organized within the figure. We will learn more about it in Chapter 3, Plotting Multiple Charts, Subplots, and Figures and Chapter 6, Plotting with Advanced Features. In this case, we are using it to get access to the axes on which we are plotting the bar graph so that we can annotate them with the actual data representing the bar. If you recall from Chapter 1, Anatomy of Matplotlib, we have seen that axes is the individual plot within the figure.
- Changing the month format from the numerical format to its corresponding month name on the x axis. calendar.month_name[1:13] will return January to December, whereas plt.xticks() changes x axis tickers from numeric 1 to 12, to January to December, for better readability.
- ax.text() within the for loop annotates each bar with its corresponding data value. Arguments for this function specify where exactly the data text has to be placed over the bar: first, get the current bar's x and y coordinates, and then add bar_width/2 to the x co-ordinate with 1.002* height being the y co-ordinate; then, using the va and ha arguments, we align the text centrally over the bar: