matplotlib之pyplot

使用pyplot绘图的基本例子

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0, 10, 1000)
y=np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y, label="$sin(x)$", color="red", linewidth=2)

plt.xlabel=("Time(s)")
plt.ylabel=("Volt")
plt.title("pyplot-y=sin(x)")
plt.ylim(-1.2, 1.2)
plt.legend()

plt.show()
plt.savefig("test.png", dpi=120) #保存图片, 后面d为设置图片的dpi 

绘制多个子图

subplot(numRows, numCols, plotNum)

如果numRows, numCols, plotNum这3个参数都小于10,那么可以将它们缩在一起。如subplot(323)和subplot(3, 2, 3)一样。
如果希望某个子图占据整行或整列,可以按照如下的形式调用subplot()

plt.subplot(221)  # 第一行的左图
plt.subplot(222)  # 第一行的右图
plt.subplot(212)  # 第二整行
import numpy as np
import matplotlib.pyplot as plt

plt.figure(1)  # 创建图1
plt.figure(2)  # 创建图2
ax1=plt.subplot(211)
ax1=plt.subplot(212)

colors='rgbyc'

x=np.linspace(0, 3, 100)
for i in xrange(5):
    plt.figure(1)  # 选择图1
    plt.plot(x, np.exp(i*x/3), color=colors(i))

    plt.sca(ax1) # 选择ax1
    plt.plot(x, np.sin(i*x))
    plt.sca(ax1) # 选择ax2
    plt.plot(x, np.cos(i*x))
plt.show()

配置文件
matplotlib的默认配置文件保存在一个名为"matplotlibrc"的配置文件中,通过修改配置文件,我们可以修改图表的默认样式。

import matplotlib
matplotlib.get_configdir()  # 获取配置文件的默认用户路径
matplotlib.matplotlib_fname()  #  目前使用的配置文件路径

为了方便对配置文件字典进行设置,可以使用rc()

matplotlib.rc("lines", marker="x", linewidth=2, color="red")

如果如此修改后,希望恢复默认的配置,可以调用

matplotlib.rcdefaults()

如果手动修改了配置文件,希望载入新的配置,可以调用

matplotlib.rcParams.update(matplotlib.rc_params())

你可能感兴趣的:(matplotlib之pyplot)