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

How it works...

The following is the explanation of the code:

  • Depts is the list of departments in the organization. rp and ra are lists of planned expenses and actual spending by department.
  • plt.figure(figsize=(10,6)) sets the figure size. plt.subplot(polar=True) sets polar projection.
  • The pyplot method accepts only radians as input, hence we need to divide 2 x np.pie (which is equivalent to 360 degrees) radians into number of departments equally, to get the angle coordinates for each of the departments. np.linspace(0, 2 * np.pi, len(rp)) does this computation. 
While the coordinates need to be given in radians, the degree equivalent is easy for visualization. To convert radians to degrees, you can use np.degrees ( theta). 
  • The default grid lines on a polar projection is 45 degrees (360 degrees divided into eight equal parts of 45 degrees each). Since we have fewer departments (only five), we need to restrict the number of grids to the number of departments.
  • plt.thetagrids(range(0,360, int(360/len(Depts))), (Depts)) function creates the grid and labels them with department names. This function also returns lines and label objects that can be used subsequently, if required.
  • plt.plot(theta, rp), plots the planned expense and fills the area with blue using plt.fill(theta, rp, 'b', alpha=0.1)
  • plt.plot(theta, ra), plots the actual expense without filling the area under it.

Finally, add a title and a legend to the plot. You should see the following chart: