matplotlib作图

类MATLAB API

  1. 加载方式
    from pylab import *
  2. 图形绘制与matlab相似
figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()

matplotlib 面向对象 API

  1. 加载方式
    import matplotlib.pyplot as plt
    使用面向对象API的方法和之前例子里的看起来很类似,不同的是,我们并不创建一个全局实例,而是将新建实例的引用保存在fig变量中,如果我们想在图中新建一个坐标轴实例,只需要 调用 fig实例的 add_axes方法:
fig = plt.figure()          
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
fig
  • 创建matplotlib.pyplot.figure实例fig
  • 调用实例方法add_axes
  • 最后使用axes的方法作图
  1. 可以使用坐标轴的位置布局,也可以使用布局管理器plt.subplots布局
  • 通过坐标轴位置布局

  • 通过布局管理器布局

图表尺寸,长宽比 与 DPI

  1. 创建800*400像素,每英寸100像素的图
    fig = plt.figure(figsize=(8,4), dpi=100)

  2. 同样的参数也可以用在布局管理器上:
    fig, axes = plt.subplots(figsize=(12,3))

保存图表savefig

fig.savefig("filename.png")
Matplotlib 可以生成多种格式的高质量图像,包括PNG,JPG,EPS,SVG,PGF 和 PDF。如果是科学论文的话,我建议尽量使用pdf格式。 (pdflatex编译的 LaTeX 文档使用 includegraphics命令就能包含 PDF 文件)。 一些情况下,PGF也是一个很好的选择。

图例,轴标 与 标题

  • 标题set_title : ax.set_title("title");
  • 轴标set_xlabelset_ylabel : ax.set_xlabel("x"), ax.set_ylabel("y");
  • 图例legend方法,或者是在调用plot方法时使用label="label text"参数,再调用legend方法加入图例
    • ax.legend(["curve1", "curve2", "curve3"]);
    • ax.plot(x, x**2, label="curve1"); ax.plot(x, x**3, label="curve2"); ax.legend();
    • legend还有一个可选参数loc决定画出图例的位置
ax.legend(loc=0) # let matplotlib decide the optimal location
ax.legend(loc=1) # upper right corne
rax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner

格式化文本,LaTeX,字体大小,字体类型

  1. Matplotlib 对 LaTeX 提供了很好的支持。我们只需要将 LaTeX 表达式封装在 符号内,就可以在图的任何文本中显示了,比如 "y=x^3"。不过这里我们会遇到一些小问题,在 LaTeX 中我们常常会用到反斜杠,比如 \alpha来产生符号\alpha$ 。但反斜杠在 python 字符串中是有特殊含义的。为了不出错,我们需要使用原始文本,只需要在字符串的前面加个r就行了,像是 r"\alpha"或者 r'\alpha'
  • LaTeX 表达式封装在$符号 : "$y=x^3$"
  • Latex 特殊字符 :"$\alpha$"或者r"\alpha"或者r'\alpha'
  • 所以使用latex文本时,使用r'$~~$' 或者r"$~~$"就可以了
  1. 更改全局字体大小或者类型,STIX 字体是一种好选择
    matplotlib.rcParams.update({'font.size': 18, 'font.family': 'STIXGeneral', 'mathtext.fontset': 'stix'})

  2. 我们也可以将图中的文本全用 Latex 渲染
    matplotlib.rcParams.update({'font.size': 18, 'text.usetex': True})

  3. 重置
    matplotlib.rcParams.update({'font.size': 12, 'font.family': 'sans', 'text.usetex': False}) # 重置

设置颜色,线宽 与 线型

  1. 颜色
  • 使用类MATLAB语法 : 'b'代表蓝色,'g'代表绿色 ...
    ax.plot(x, x**2, 'b.-') # blue line with dots
    ax.plot(x, x**3, 'g--') # green dashed line
    
  • 使用颜色的名字或者RGB值选择颜色,alpha参数决定了颜色的透明度:
ax.plot(x, x+1, color="red", alpha=0.5) # half-transparant red
ax.plot(x, x+2, color="#1155dd") # RGB hex code for a bluish color
ax.plot(x, x+3, color="#15cc55") # RGB hex code for a greenish color
  1. 线与描点风格
  • linewidth或是lw参数改变线宽。
  • linestyle或是ls参数改变线的风格。

控制坐标轴的样式

  1. 图的范围
  • Auto调整 :axes.axis('tight')
  • Custom调整 :axes.set_ylim([0, 60]); axes.set_xlim([2, 5])
  1. 对数刻度 调用 set_xscaleset_yscale设置刻度
    axes.set_yscale("log")

其他 2D 图表风格

n = array([0,1,2,3,4,5])
fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(xx, xx + 0.25*randn(len(xx)))      #scatter
axes[0].set_title("scatter")
axes[1].step(n, n**2, lw=2)            #step
axes[1].set_title("step")
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)      #bar
axes[2].set_title("bar")
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5)  #fill_between
axes[3].set_title("fill_between")
fig
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容