上QQ阅读APP看书,第一时间看更新
How it works...
The following is the explanation of the code:
- rows is the list of years and columns is the list of battery ratings. They are plotted as rows and columns of the table in the plot.
- data is the number of units sold for each rating of the battery, in a given year, for example, 75 units of 7 Ah batteries sold in 2011.
- values is the list specifying the scale for the y axis with increments of 100, starting with zero, up to six hundred. This being a stacked bar chart, it should cover the sum total of a given battery rating across all years (the maximum in this case is 576).
- plt.cm.OrRd() specifies the range of colors with varying intensity; there are pre-defined colormaps in Matplotlib. We will cover these in Chapter 4, Developing Visualizations for Publishing Quality. Here, it is used to display each year data in a different color.
- index specifies the placement of each bar on the x axis, and bar_width specifies the width of each bar.
- y_offset represents where each year's data should start on the y axis, as each year's data is stacked one over the other. Start at the bottom with zero and keep adding for each year.
- When the for loop is initiated, each iteration plots bars for all battery ratings for a given year, and then another for loop to annotate each bar with the corresponding data label.
- Arguments in the second for loop specify the exact location for the data text to be placed over the bar. First, get the current bar x and y coordinates, then add bar_width/2 to the x coordinate and y_offset[i] gives us the y coordinate; then, using va and ha, the arguments align the text over the bar, centrally.
- Then add Y-label, title and mask X-ticks.
Here is how the plot looks: