导读
本章主要知识点:
- 在同一个坐标画不同的元素
- plt.close('all')清空画布中的所有元素
- plt.subplot(xxx)灵活分割一个figure
- plt.subplots(x,y)分割一个figure
- plt.subplot2grid()网格分割一个figure
- plt.figure(x)生成多个figure
代码环境约定
matplot系列文章默认运行在jupyterlab中,所有代码cell都在以下代码环境后运行
import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
# 全局配置
mpl.rcdefaults()
mpl.rcParams['font.family'] = "Microsoft YaHei"
mpl.rcParams["axes.unicode_minus"] = True # 正常显示负号
plt.style.use('ggplot')
在一个坐标轴画多元素
x = np.arange(1,11,1)
# y参数传递2维数组
plt.plot(x, np.random.randint(20,50,30).reshape(10,-1));
plt.plot(x, np.arange(1,100,10))
plt.plot(x, np.linspace(30,50,10))
plt.plot(x, 100*np.random.rand(10));
多坐标作图plt.subplots()
# subplot分割当前figure
plt.close('all') #清空画布中的元素
fig = plt.figure()
# 两行两列第一个
ax1 = plt.subplot(221)
# 两行两列第二个
ax2 = plt.subplot(222)
# 两行一列第二个,因为第一个位置被ax1和ax2占领
ax3 = plt.subplot(212)
ax1.plot([1,2,3])
ax2.plot([3,2,1])
ax3.plot([2,5,4])
plt.tight_layout();
# plt.shplots()
wine_quality = pd.read_csv('winequality.csv', delimiter=';')
iris = pd.read_csv('iris_dataset.csv', delimiter=',')
iris = iris.drop('species',axis=1)
iris_mean = iris.mean()
iris_std = iris.std()
# 将figure分割成两行两列共4个坐标系
fig, axs = plt.subplots(2, 2, figsize=(8, 8))
axs[0, 0].hist(wine_quality['alcohol'])
axs[0, 0].set(title='直方图', xlabel='Alcohol Bins', ylabel='Frequency')
axs[0, 1].plot(iris['sepal_length'], iris['sepal_width'])
axs[0, 1].set(title='折线图', xlabel='Sepal Length', ylabel='Sepal Width')
axs[1, 0].scatter(iris['petal_length'], iris['petal_width'])
axs[1, 0].set(title='散点图', xlabel='Petal Length', ylabel='Petal Width')
axs[1, 1].bar(['sepal_l','sepal_w', 'petal_l', 'petal_w'], iris_mean, yerr=iris_std)
axs[1, 1].set(title='条形图', xlabel='Category', ylabel='Category Mean')
plt.suptitle('plt.subplots(2,2)')
plt.tight_layout(pad=3, w_pad=1.0, h_pad=1.0);
多个figure:plt.figure(num)
# 多figure
plt.close('all')
iris = pd.read_csv('iris_dataset.csv', delimiter=',')
fig = plt.figure(1, figsize=(10, 7))
# 网格分割figure1
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)
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'])
plt.suptitle('figure 1:网格分割', fontsize=15)
plt.tight_layout()
# subplot分割figure2
plt.figure(2, figsize=(10, 4))
names = ['A', 'B', 'C', 'D', 'E']
values = [1, 10, 50, 100, 500]
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('figure 2: subplot分割', fontsize=15)
plt.tight_layout(pad=1);
本文章参考《Matplotlib 3.0 Cookbook》,作者:Srinivasa Rao Poladi
欢迎各位看官关注、转发、收藏、评论,thanks by 渝玖玖