什么是Matplotlib

引用维基百科中的定义,Matplotlib是Python编程语言及其数学扩展包Numpy的可视化操作界面。通过利用Tkinter、wxPython、QT、GTK+等通用图形用户界面工具包,为应用程序嵌入式绘图提供了API。此外,它还有一个基于图像处理库的pylab接口,其设计与Matlab十分相似;

如何使用Matplotlib

我将通过代码实例的形式给出Matplotlib的使用方法,具体情况如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/21 9:59
# @Author  : Cunyu
# @Site    : cunyu1943.github.io
# @File    : matplotlib_examples.py
# @Software: PyCharm

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

\"\"\"
基本使用
\"\"\"
x = np.linspace(-5, 5, 100)
y1 = 2 * x +5
y2 = x ** 2

# 定义一个图像窗口,并画出图像
plt.figure(num=1, figsize=(8,5))
plt.plot(x, y1, label = \'linear\', color = \'red\', linestyle=\'--\')
plt.plot(x, y2, label = \'square\', color = \'blue\')

# 调整坐标轴名字及其间隔
plt.ylim(-5, 20)
plt.xlim(-5, 5)
plt.xlabel(\'x\')
plt.ylabel(\'y\')

# 设置坐标轴刻度及对应名
new_ticks = np.linspace(-5, 4, 10)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-3, -1, 3, 10, 18],[r\'$really\\ bad$\', r\'$bad$\', r\'$normal$\', r\'$good$\', r\'$really\\ good$\'])

# 获取坐标轴信息
ax = plt.gca()

# 设置边框信息,将上边框和右边框设置为不同颜色,默认是白色
ax.spines[\'right\'].set_color(\'green\')
ax.spines[\'top\'].set_color(\'purple\')

# 调整坐标轴位置
ax.spines[\'left\'].set_position((\'data\', 1))
ax.spines[\'bottom\'].set_position((\'data\', 0))

\"\"\"
Legend图例,添加图例
添加位置参数:
 \'best\' : 0,          
 \'upper right\'  : 1,
 \'upper left\'   : 2,
 \'lower left\'   : 3,
 \'lower right\'  : 4,
 \'right\'        : 5,
 \'center left\'  : 6,
 \'center right\' : 7,
 \'lower center\' : 8,
 \'upper center\' : 9,
 \'center\'       : 10,
\"\"\"
plt.legend(loc = \'upper right\') # 显示在右上角

# 添加注释
plt.text(0, 0, r\'This is (0, 0).\', fontdict={\'size\':14, \'color\':\'red\'})
# 显示图像
plt.show()
plt.close()

\"\"\"
画图种类
\"\"\"
# 散点图
SIZE = 1024
x = np.random.normal(0, 1, SIZE)
y = np.random.normal(0, 1, SIZE)
T = np.arctan2(y, x)
plt.scatter(x, y, s=75, c=T, alpha=.5)
plt.show()
plt.close()

# bar柱状图
x = np.arange(15)
Y1 = (1 - x / float(15)) * np.random.uniform(0.5, 1.0, 15)
Y2 = (1 - x / float(15)) * np.random.uniform(0.5, 1.0, 15)
plt.bar(x, Y1, edgecolor =\'black\',facecolor=\'red\')
plt.bar(x, -Y2, edgecolor =\'yellow\',facecolor=\'blue\')
for x, y in zip(x,Y1):
    plt.text(x+0.1,y+0.1,\'%.2f\' % y, ha=\'center\',va=\'bottom\')
plt.show()
plt.close()

# 随机矩阵画图
a=np.array(np.random.rand(12)).reshape(3,4)
plt.imshow(a, interpolation=\'none\', cmap=\'bone\', origin=\'lower\')
plt.colorbar(shrink=.1)
plt.xticks(())
plt.yticks(())
plt.show()
plt.close()

# 3D图
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(-5, 5, .5)
y = np.arange(-5, 5, .25)
x,y = np.meshgrid(x, y)
r = np.sqrt(x**2,y**2)
z=np.sin(r)
ax.plot_surface(x,y,z,cmap=plt.get_cmap(\'rainbow\'),rstride=1,cstride=1)
# 投影
ax.contourf(x,y,z,zdir=\'y\',offset=2,cmap=plt.get_cmap(\'rainbow\'))
plt.show()
plt.close()

\"\"\"
多图合并显示
\"\"\"
# 1、subplot多合一显示
plt.figure()

# 将整个图像窗口均匀分为2行2列
plt.subplot(2,2,1)
plt.plot([0, 1], [0,1])
plt.subplot(2,2,2)
plt.plot([0, 1], [0,5])
plt.subplot(2,2,3)
plt.plot([0, 1], [0,10])
plt.subplot(2,2,4)
plt.plot([0, 1], [0,15])
plt.show()
plt.close()

# 将整个图像窗口不均匀划分
plt.subplot(2,1,1)
plt.plot([0, 1], [0,1])
plt.subplot(2,3,4)
plt.plot([0, 1], [0,5])
plt.subplot(2,3,5)
plt.plot([0, 1], [0,10])
plt.subplot(2,3,6)
plt.plot([0, 1], [0,15])
plt.show()
plt.close()

import matplotlib.gridspec as gridspec
# 2、subplot分格显示
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])
plt.show()
plt.close()

# 3、图中图
# 数据准备
fig = plt.figure()
x = np.arange(6)
y = x**2
print(x)
print(y)

# 大图
ax1 = fig.add_axes([.1, .1, .8, .8])
ax1.plot(x,y,\'r\')
ax1.set_xlabel(\'x\')
ax1.set_ylabel(\'y\')
ax1.set_ (\' \')
# 小图
ax2 = fig.add_axes([.2,.5,.25,.25])
ax2.plot(y,x,\'b\')
ax2.set_xlabel(\'x\')
ax2.set_ylabel(\'y\')
ax2.set_ (\'  inside 1\')
plt.show()
plt.close()

# 4、次坐标轴
# 第一个坐标轴y
x = np.arange(0, 10, 0.1)
y1 = x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
# 第二个坐标轴
ax2 = ax1.twinx()
ax1.plot(x, y1, \'g-\')   # green, solid line
ax1.set_xlabel(\'X data\')
ax1.set_ylabel(\'Y1 data\', color=\'g\')
ax2.plot(x, y2, \'b-\') # blue
ax2.set_ylabel(\'Y2 data\', color=\'b\')
plt.show()
plt.close()
收藏 打印