Python矩阵作图库matplotlib的初级使用(2)
-
基础介绍
matplotlib图形对象层级结构:
图形对象(figure) → 子图对象(axes) → 坐标轴对象(axis) → 定位器对象-刻度线(locator)/格式化器对象-刻度线标签(formatter) -
绘图对象创建
from matplotlib import pyplot as plt # 创建绘图对象 fig = plt.figure() # 创建网格子图 ax1 = fig.add_subplot(rows, cols, idx) # 创建手动子图 ax1 = fig.add_axes([left, bottom, width, height]) # 获取坐标轴对象 ax1.xaxis ax1.yaxis # 设置定位器对象 ax1.xaxis.set_major_locator(plt.NullLocator) ax1.xaxis.set_minor_locator(plt.NullLocator) # 设置格式化器对象 ax1.xaxis.set_major_formatter(plt.NullFormatter) ax1.xaxis.set_minor_formatter(plt.NullFormatter)
-
部分细节控制
-
颜色支持
①. 标准颜色名称, 如: "red"
②. 范围在0~1的灰度值, 如: "0.75"
③. RGB十六进制, 如: "#FFDD44"
④. RGB元组, 范围在0~1, 如: (1.0, 0.2, 0.3) -
配色方案支持
①. 获取配色方案: plt.cm
②. 常见配色方案: "jet", "viridis", "RdBu"
③. 离散化配色方案: plt.cm.get_cmap("Blues", 6) -
颜色条控制支持
plt.colorbar(mappable, ticks=range(6), label="digit value", extend="both")
注意, colorbar本身也是一个子图对象, 创建时依赖于mappable对象 -
linestyle线条风格支持
①. "solid"; ②. "dashed"; ③. "dashdot"; ④. "dotted" -
散点控制支持
①. markersize; ②. markerfacecolor; ③. markeredgecolor; ④. markeredgewidth
注意, 绘制散点时, plt.plot较plt.scatter性能更好, plt.scatter较plt.plot更加灵活 -
标签支持
①. title; ②. xlabel; ③. ylabel; ④. label; ⑤. legend -
图例控制支持
ax1.legend([labels,] loc="upper left", frameon=False, ncol=2, fontsize=10, title="Area") -
文本注释支持
ax1.text(x, y, text, size, color, ha, va, transform=ax1.transData|ax1.transAxes|fig.transFigure) -
坐标轴控制支持
ax1.set(xlabel, xlim, xticks, xscale)
-
-
部分绘图实例
-
误差绘制
code
import numpy from matplotlib import pyplot as plt X = numpy.linspace(-1, 1, 30) Y = X ** 3 + X ** 2 + X YErr = numpy.random.uniform(0.3, 0.7, Y.shape) fig = plt.figure(figsize=(4, 4)) ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) ax1.errorbar(X, Y, YErr, fmt="o", color="black", ecolor="lightgray", elinewidth=3, capsize=0) ax2.plot(X, Y, "-", color="gray") ax2.fill_between(X, Y-YErr, Y+YErr, color="gray", alpha=0.2) fig.savefig("plot.png", dpi=300)
-
等高线绘制
code
import numpy from matplotlib import pyplot as plt X = numpy.linspace(-1, 1, 30) Y = numpy.linspace(-2, 2, 50) X, Y = numpy.meshgrid(X, Y) Z = numpy.sin(X) + numpy.cos(Y ** 2) fig = plt.figure(figsize=(10, 3)) ax1 = fig.add_axes([0.1, 0.1, 0.3, 0.9]) ax2 = fig.add_axes([0.5, 0.1, 0.3, 0.9]) ax1.contourf(X, Y, Z, 20, cmap="RdGy") ax2.imshow(Z, extent=[-1, 1, -2, 2], origin="lower", cmap="RdGy", aspect="auto") fig.savefig("plot.png", dpi=300)
-
3维曲面绘制
code
import numpy from matplotlib import pyplot as plt from mpl_toolkits import mplot3d X = numpy.linspace(-1, 1, 30) Y = numpy.linspace(-2, 2, 50) X, Y = numpy.meshgrid(X, Y) Z = numpy.sin(X) + numpy.cos(Y ** 2) fig = plt.figure(figsize=(10, 3)) ax1 = fig.add_subplot(1, 2, 1, projection="3d") ax2 = fig.add_subplot(1, 2, 2, projection="3d") ax1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="viridis", edgecolor="none") ax2.plot_trisurf(X.flatten(), Y.flatten(), Z.flatten(), cmap="viridis", edgecolor="none") fig.tight_layout() fig.savefig("plot.png", dpi=300)
-
直方图与密度图
code
import numpy import seaborn as sns from matplotlib import pyplot as plt X = numpy.random.normal(0, 1, (10000,)) fig = plt.figure(figsize=(10, 3)) ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) sns.histplot(X, kde=False, ax=ax1) sns.kdeplot(data=X, ax=ax2) fig.savefig("plot.png", dpi=300)
-
多维矩阵图
code
import numpy import pandas import seaborn as sns X1 = numpy.random.normal(0, 1, (300,)) X2 = numpy.sin(X1) X3 = X1 ** 2 data = numpy.vstack((X1, X2, X3)).T df = pandas.DataFrame(data, columns=["X1", "X2", "X3"]) sns_plot = sns.pairplot(df) sns_plot.savefig("plot.png", dpi=300)
-
-
参考文档
①. Python Data Science Handbook by Jake VanderPlas (O’Reilly). Copyright 2017 Jake VanderPlas, 978-1-491-91205-8