Matplotlib
Getting Started
基础使用
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
一个简单的例子
Matplotlib 将你的数据显示在Figure上,每个图片可以包含一个或以上的坐标域(Axes:一个可以用x-y坐标、极坐标、三维坐标表示特定点的区域),通过pyplot.subplots
可以创建一个带有坐标的Figure,可以使用Axes.plot
在坐标域中画一些数据,例如
fig, ax = plt.subplots() # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # Plot some data on the axes.
Figure的组成
Figure可以包含图中的部分
最简单的创建一个新的Figure的方式是使用pyplot
,下面是创建几种不同样式的Figure的例子
fig = plt.figure() # an empty figure with no Axes
fig, ax = plt.subplots() # a figure with a single Axes
fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
Artist
任何在Figure中可见的元素都被称为Artist,大多数Artist都被绑定至一个Axes
Axes
Axes是Figure中作为绘图的区域,通常包含2个或3个坐标轴(Axis)以及相应的坐标间隔尺度等
绘图函数的输入变量类型
绘图函数期望输入的类型是numpy.array
或numpy.ma.masked_array
,
或者是可以被转换为numpy.asarray
的数据。一些类数组(array-like)的数据类,例如pandas
以及numpy.matrix
可能不会像你想要的方式运行,通常先将它们转换为numopy.asarray
类型再进行绘图,例如
b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b)
大多数方法(methods)也会解析一些寻址类型的数据类型,例如dict
,numpy.rearray
,pandas.dataFrames
。Matplotlib allows you provide the data keyword argument and generate plots passing the strings corresponding to the x and y variables.
np.random.seed(19680801) # seed the random number generator.
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b');
编码风格
将常用绘图方式打包成一个函数
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph.
"""
out = ax.plot(data1, data2, **param_dict)
return out
data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data sets
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
Artists Styles
大多数绘制方法具有Styles可选项,可以通过plot
人为设置颜色、线宽、线型等
fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1))
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--')
l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2)
l.set_linestyle(':')
颜色
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k')
线宽、线型、标识符
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(data1, 'o', label='data1')
ax.plot(data2, 'd', label='data2')
ax.plot(data3, 'v', label='data3')
ax.plot(data4, 's', label='data4')
ax.legend()
添加标签
坐标域标签和文字
set_xlabel, set_ylabel, set_title, text
mu, sigma = 115, 15
x = mu + sigma * np.random.randn(10000)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# the histogram of the data
n, bins, patches = ax.hist(x, 50, density=1, facecolor='C0', alpha=0.75)
ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Aardvark lengths\n (not really)')
ax.text(75, .025, r'$\mu=115,\ \sigma=15$')
ax.axis([55, 175, 0, 0.03])
ax.grid(True)
数学表达式
Matplotlib接受Tex的方程表达式,例如 σ i = 15 \sigma_i = 15 σi=15
ax.set_title(r'$\sigma_i=15$')
附注(Annotations)
fig, ax = plt.subplots(figsize=(5, 2.7))
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = ax.plot(t, s, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.set_ylim(-2, 2)
图例(legends)
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(np.arange(len(data1)), data1, label='data1')
ax.plot(np.arange(len(data2)), data2, label='data2')
ax.plot(np.arange(len(data3)), data3, 'd', label='data3')
ax.legend()
坐标轴尺度和刻度
尺度
loglog, semilogx, semilogy
fig, axs = plt.subplots(1, 2, figsize=(5, 2.7), layout='constrained')
xdata = np.arange(len(data1)) # make an ordinal for this
data = 10**data1
axs[0].plot(xdata, data)
axs[1].set_yscale('log')
axs[1].plot(xdata, data)
刻度位置和格式
set_xticks
fig, axs = plt.subplots(2, 1, layout='constrained')
axs[0].plot(xdata, data1)
axs[0].set_title('Automatic ticks')
axs[1].plot(xdata, data1)
axs[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90'])
axs[1].set_yticks([-1.5, 0, 1.5]) # note that we don't need to specify labels
axs[1].set_title('Manual ticks')
绘制日期和字符串
未完待续