Python的Matplotlib模块

Matplotlib是Python的一个绘图库,包含了大量创建图形的工具,例如散点图,三角函数曲线,三维图形等。

引用模块方式

由于from x import * 是一种糟糕的导入方式,同时不想在程序里重复书写过于冗长的matplotlib.pyplot和numpy,因此我们采用下面的写法:

import matplotlib.pyplot as plt
import numpy as np

绘图三大系统

  1. pyplot
    使用plt.style.use('ggplot')命令,可以作出ggplot风格的图片。
  2. pylab(不推荐)
  3. 面向对象

绘图

  1. 散点图
x = rand(50,30)  
plt.scatter(x[:,1],x[:,0],marker = 'x', color = 'm', label='1', s = 30)
plt.show()
# or
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x,y,'o')
plt.show()
  1. 折线图
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x,y)
plt.show()
  1. 条形图
mean_values = [1, 2, 3]
variance = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
x_pos = list(range(len(bar_labels)))
plt.bar(x_pos, mean_values, yerr=variance, align='center', alpha=0.5)
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with error bars')
plt.show()
#参见:http://blog.topspeedsnail.com/archives/724
  1. 直方图
    函数:histogram() 或 hist()

  2. 饼状图
    函数:pie()

  3. 箱形图
    函数:boxplot() 或 plot.box()

图形美化

  1. 确定坐标范围
plt.axis([xmin, xmax, ymin, ymax]) #给定了坐标范围
xlim(xmin, xmax) #调整x坐标范围
ylim(ymin, ymax) #调整y坐标范围
  1. 添加文字说明
    在图中的任意位置添加文字:text() 支持LaTex语法
    添加x轴和y轴标签:xlable(), ylable()
    添加图的题目:title()
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

#数据的直方图
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)

plt.xlabel('Smarts')
plt.ylabel('Probability')

#添加标题
plt.title('Histogram of IQ')

#添加文字
plt.text(60, .025, r'$mu=100, sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)

plt.show()
  1. 添加图片注释
    函数:annotate()
ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2,1), xytext=(3,1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),)
plt.ylim(-2,2)
plt.show()
  1. 设置坐标轴刻度
    函数:xticks()/ yticks(),为x,y轴的刻度设置颜色、大小、方向,以及标签大小。

  2. 设置坐标轴体系-Axes对象
    函数:axes(rect=[左,下,宽,高],axisbg='y')
    设置坐标轴边界和表面的颜色、坐标刻度值大小和网格的显示。

  3. 添加图例
    函数:legend()

plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plot(X, S, color="red",  linewidth=2.5, linestyle="-", label="sine")
legend(loc='upper left')
  1. 叠加图
t = np.arange(0., 5., 0.2)
#red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g<')
plt.show()
  1. 多张图
    创建新图:figure()
    创建子图:subplot()。其中,subplot(2,3,1)表示把图标分割成2*3的网格,也可以简写plt.subplot(231)。第一个参数是行数,第二个参数是列数,第三个参数表示图形的标号。
plt.figure(1)      # 第一张图
plt.subplot(211)   # 第一张图中的第一张子图
plt.plot([1,2,3])
plt.subplot(212)   # 第一张图中的第二张子图
plt.plot([4,5,6])

plt.figure(2)      # 第二张图
plt.plot([4,5,6])  # 默认创建子图subplot(111)

plt.figure(1)      # 切换到figure(1)
plt.subplot(211)   # 切换到figure(1)的子图subplot(211)
plt.title('Easy as 1,2,3') # 添加subplot(211)的标题

plt.show()
  1. 图形正常显示中文
    函数:rcParams()
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False   #用来正常显示负号
  1. 保存图片
    函数:savefig()
plt.plot([1,2,3],'r--')
plt.savefig('D:\\test.pdf',dpi=600, format="pdf") #png, pdf, ps, eps and svg
plt.show()

图形标记

*1. 线条类型

标记 描述 标记 描述
'-' 实线 ':' 虚线
'--' 破折线 '-.' 点划线
'None' / ' ' / '' 什么都不画

*2. 线条标记

标记 描述 标记 描述
'o' 实心圆圈 '.'
'D' 实心菱形 's' 实心正方形
'h' 竖六边形 '*' 星号
'H' 横六边形 'd' 瘦菱形
'_' 水平线 '+' 加号
'8' 实心八边形 竖线
'p' 实心五边形 ',' 像素标记(极小点)
'v' 下三角标记 '<' 左三角标记
'>' 右三角标记 '^' 上三角标记
'1' 下花三角标记 '2' 上花三角标记
'3' 左花三角标记 '4' 右花三角标记

*3. 颜色标记

标记 描述 标记 描述
'b' 蓝色 'g' 绿色
'r' 红色 'y' 黄色
'c' 青色 'k' 黑色
'm' 洋红色 'w' 白色

参考

https://matplotlib.org/contents.html