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

How to do it...

Since it is a circular spider web, we need to connect the last point to the first point, so that there is a circular flow of the graph. To achieve this, we need to repeat the first department data point at the end of the list again. Hence, in the following example, 30 and 32 (the first entry in each of the lists) are repeated at the end again.

The following code block plots a polar graph and displays it on the screen:

  1. Set up the data for a polar plot:
Depts = ["COGS","IT","Payroll","R & D", "Sales & Marketing"]
rp = [30, 15, 25, 10, 20, 30]
ra = [32, 20, 23, 11, 14, 32]
theta = np.linspace(0, 2 * np.pi, len(rp))
  1. Initialize the spider plot by setting figure size and polar projection:
plt.figure(figsize=(10,6))
plt.subplot(polar=True)
  1. Arrange the grid lines to align with each of the department names:
(lines,labels) = plt.thetagrids(range(0,360, int(360/len(Depts))),
(Depts))
  1. Plot the planned spend graph, which is a line plot on polar coordinates, and then fill the area under it:
plt.plot(theta, rp)
plt.fill(theta, rp, 'b', alpha=0.1)
  1. Plot the actual spend graph, which is a line plot on polar coordinates:
plt.plot(theta, ra)
  1. Add a legend and a title for the plot:
plt.legend(labels=('Plan','Actual'),loc=1)
plt.title("Plan vs Actual spend by Department")
  1. Display the plot on the screen:
plt.show()