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

How to do it...

The following code block plots two figures with multiple plots in each:

  1. Read the Iris data from Excel:
iris = pd.read_csv('iris_dataset.csv', delimiter=',')
  1. Clear the canvas to start a new figure:
plt.close('all')
  1. Define figure 1 and the associated layout and subplots:
fig = plt.figure(1, figsize=(12, 9))
ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

  1. Plot the graphs on each of the four axes defined in step 3:
ax1.hist(iris['petal_width'])
ax2.scatter(iris['petal_length'], iris['petal_width'], s=50*iris['petal_length']*iris['petal_width'], alpha=0.3)
ax3.scatter(iris['sepal_length'], iris['sepal_width'])
ax4.violinplot(iris['petal_length'])
  1. Set the title and adjust the space between the plots:
plt.suptitle('Figure 1: Grid Plotting Demo', fontsize=20)
plt.tight_layout(pad=5, w_pad=0.5, h_pad=1.0)
  1. Define the figure 2 and its size:
plt.figure(2, figsize=(12, 5))
  1. Set up the data for the bar plot:
names = ['group_a', 'group_b', 'group_c', 'group_d', 'group_e']
values = [1, 10, 50, 100, 500]
  1. Define the first axis and plot the bar graph:
plt.subplot(131)
plt.bar(names, values, color='orange')
  1. Define the second axis and plot a scatter plot:
plt.subplot(132)
plt.scatter(names, values, color='orange')
  1. Define the third axis and a line graph:
plt.subplot(133)
plt.plot(names, values, color='orange')
  1. Set the title for the overall figure and adjust the space between the plots in the figure:
plt.suptitle('Figure 2: Row Plotting Demo', fontsize=20)
plt.tight_layout(pad=5, w_pad=0.5, h_pad=1.0)
  1. Display the figure on the screen:
plt.show()