Matplotlib
一 簡介:
Matplotlib是一個Python 2D繪圖庫,它可以在各種平臺上以各種硬拷貝格式和交互式環境生成出具有出版品質的圖形。 Matplotlib可用于Python腳本,Python和IPython shell,Jupyter筆記本,Web應用程序服務器和四個圖形用戶界面工具包
Matplotlib試圖讓簡單的事情變得更簡單,讓無法實現的事情變得可能實現。 只需幾行代碼即可生成繪圖,直方圖,功率譜,條形圖,錯誤圖,散點圖等。 有關示例,請參閱示例圖和縮略圖庫。
為了簡單繪圖,pyplot模塊提供了類似于MATLAB的界面,特別是與IPython結合使用時。 對于高級用戶,您可以通過面向對象的界面或MATLAB用戶熟悉的一組函數完全控制線條樣式,字體屬性,軸屬性等。
二 相關文檔:
三 入門與進階案例
1- 簡單圖形繪制
根據坐標點繪制:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([3,5,7,6,2,6,10,15])
plt.plot(x,y,'r')# 折線 1 x 2 y 3 color
plt.plot(x,y,'g',lw=10)# 4 line w
# 折線 餅狀 柱狀
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([13,25,17,36,21,16,10,15])
plt.bar(x,y,0.2,alpha=1,color='b')# 5 color 4 透明度 3 0.9
plt.show()
傳入參數是numpy數組時的效果:
import numpy as np
import matplotlib.pyplot as plt
for i in range(0,15):
# 1 柱狀圖
dateOne = np.zeros([2])
dateOne[0] = i;
dateOne[1] = i;
y = np.zeros([2])
y[0] = 10
y[1] = 20
plt.plot(dateOne,y,'r',lw=8)
plt.show()
根據函數圖像繪制:
# -*- coding: utf-8 -*-
"""
簡單圖形繪制
"""
import matplotlib.pyplot as plt
import numpy as np
#從-1-----1之間等間隔采66個數.也就是說所畫出來的圖形是66個點連接得來的
#注意:如果點數過小的話會導致畫出來二次函數圖像不平滑
x = np.linspace(-1, 1,66)
# 繪制y=2x+1函數的圖像
y = 2 * x + 1
plt.plot(x, y)
plt.show()
# 繪制x^2函數的圖像
y = x**2
plt.plot(x, y)
plt.show()
2- figure的簡單使用
# -*- coding: utf-8 -*-
"""
figure的使用
"""
import matplotlib.pyplot as plt
import numpy as np
#
x = np.linspace(-1, 1, 50)
# figure 1
y1 = 2 * x + 1
plt.figure()
plt.plot(x, y1)
# figure 2
y2 = x**2
plt.figure()
plt.plot(x, y2)
# figure 3,指定figure的編號并指定figure的大小, 指定線的顏色, 寬度和類型
#一個坐標軸上畫了兩個圖形
y2 = x**2
plt.figure(num = 5, figsize = (4, 4))
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
plt.show()
一共會畫出三張圖,前兩張和上面的簡單案例畫出來的兩張一樣。第三張:
3- 設置坐標軸
# -*- coding: utf-8 -*-
"""
設置坐標軸
"""
import matplotlib.pyplot as plt
import numpy as np
# 繪制普通圖像
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
# 設置坐標軸的取值范圍
plt.xlim((-1, 1))
plt.ylim((0, 3))
# 設置坐標軸的lable
#標簽里面必須添加字體變量:fontproperties='SimHei',fontsize=14。不然可能會亂碼
plt.xlabel(u'這是x軸',fontproperties='SimHei',fontsize=14)
plt.ylabel(u'這是y軸',fontproperties='SimHei',fontsize=14)
# 設置x坐標軸刻度, 之前為0.25, 修改后為0.5
#也就是在坐標軸上取5個點,x軸的范圍為-1到1所以取5個點之后刻度就變為0.5了
plt.xticks(np.linspace(-1, 1, 5))
plt.show()
上面代碼的基礎上加上下面代碼(直接加載最后一句代碼前面即可):
# 獲取當前的坐標軸, gca = get current axis
ax = plt.gca()
# 設置右邊框和上邊框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 設置x坐標軸為下邊框
ax.xaxis.set_ticks_position('bottom')
# 設置y坐標軸為左邊框
ax.yaxis.set_ticks_position('left')
# 設置x軸, y周在(0, 0)的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
如果在上面代碼的最后一句之前加上下面的代碼:
# 設置坐標軸label的大小,背景色等信息
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor = 'green', edgecolor = 'None', alpha = 0.7))
4- 設置legend圖例
# -*- coding: utf-8 -*-
"""
設置坐標軸
"""
import matplotlib.pyplot as plt
import numpy as np
# 繪制普通圖像
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
# 設置坐標軸的取值范圍
plt.xlim((-1, 1))
plt.ylim((0, 3))
# 設置坐標軸的lable
#標簽里面必須添加字體變量:fontproperties='SimHei',fontsize=14。不然可能會亂碼
plt.xlabel(u'這是x軸',fontproperties='SimHei',fontsize=14)
plt.ylabel(u'這是y軸',fontproperties='SimHei',fontsize=14)
# 設置x坐標軸刻度, 之前為0.25, 修改后為0.5
#也就是在坐標軸上取5個點,x軸的范圍為-1到1所以取5個點之后刻度就變為0.5了
plt.xticks(np.linspace(-1, 1, 5))
# 獲取當前的坐標軸, gca = get current axis
ax = plt.gca()
# 設置右邊框和上邊框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 設置x坐標軸為下邊框
ax.xaxis.set_ticks_position('bottom')
# 設置y坐標軸為左邊框
ax.yaxis.set_ticks_position('left')
# 設置x軸, y周在(0, 0)的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()
5- 添加注解和繪制點以及在圖形上繪制線或點
# -*- coding: utf-8 -*-
"""
添加注解和繪制點以及在圖形上繪制線或點
"""
import matplotlib.pyplot as plt
import numpy as np
# 繪制普通圖像
x = np.linspace(-3, 3, 50)
y = 2 * x + 1
plt.figure()
plt.plot(x, y)
# 將上、右邊框去掉
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 設置x軸的位置及數據在坐標軸上的位置
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
# 設置y軸的位置及數據在坐標軸上的位置
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 定義(x0, y0)點
x0 = 1
y0 = 2 * x0 + 1
# 繪制(x0, y0)點
plt.scatter(x0, y0, s = 50, color = 'blue')
# 繪制虛線
plt.plot([x0, x0], [y0, 0], 'k--', lw = 2.5)
# 繪制注解一
plt.annotate(r'$2 * x + 1 = %s$' % y0, xy = (x0, y0), xycoords = 'data', xytext = (+30, -30), \
textcoords = 'offset points', fontsize = 16, arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3, rad = .2'))
# 繪制注解二
plt.text(-3, 3, r'$Test\ text. \mu \sigma_i, \alpha_i$', fontdict = {'size': 16, 'color': 'red'})
plt.show()
6- 繪制散點圖
# -*- coding: utf-8 -*-
"""
繪制散點圖
"""
import numpy as np
import matplotlib.pyplot as plt
# 數據個數
n = 1024
# 均值為0, 方差為1的隨機數
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
# 計算顏色值
color = np.arctan2(y, x)
# 繪制散點圖
plt.scatter(x, y, s = 75, c = color, alpha = 0.5)
# 設置坐標軸范圍
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))
# 不顯示坐標軸的值
plt.xticks(())
plt.yticks(())
plt.show()
7- 繪制柱狀圖
# -*- coding: utf-8 -*-
"""
繪制柱狀圖
"""
import matplotlib.pyplot as plt
import numpy as np
# 數據數目
n = 10
x = np.arange(n)
# 生成數據, 均勻分布(0.5, 1.0)之間
y1 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
# 繪制柱狀圖, 向上
plt.bar(x, y1, facecolor = 'blue', edgecolor = 'white')
# 繪制柱狀圖, 向下
plt.bar(x, -y2, facecolor = 'green', edgecolor = 'white')
temp = zip(x, y2)
# 在柱狀圖上顯示具體數值, ha水平對齊, va垂直對齊
for x, y in zip(x, y1):
plt.text(x + 0.05, y + 0.1, '%.2f' % y, ha = 'center', va = 'bottom')
for x, y in temp:
plt.text(x + 0.05, -y - 0.1, '%.2f' % y, ha = 'center', va = 'bottom')
# 設置坐標軸范圍
plt.xlim(-1, n)
plt.ylim(-1.5, 1.5)
# 去除坐標軸
plt.xticks(())
plt.yticks(())
plt.show()
8- 繪制登高線圖
# -*- coding: utf-8 -*-
"""
繪制登高線圖
"""
import matplotlib.pyplot as plt
import numpy as np
# 定義等高線高度函數
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)
# 數據數目
n = 256
# 定義x, y
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
# 生成網格數據
X, Y = np.meshgrid(x, y)
# 填充等高線的顏色, 8是等高線分為幾部分
plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.hot)
# 繪制等高線
C = plt.contour(X, Y, f(X, Y), 8, colors = 'black', linewidth = 0.5)
# 繪制等高線數據
plt.clabel(C, inline = True, fontsize = 10)
# 去除坐標軸
plt.xticks(())
plt.yticks(())
plt.show()
9- 繪制Image
# -*- coding: utf-8 -*-
"""
繪制Image
"""
import matplotlib.pyplot as plt
import numpy as np
# 定義圖像數據
a = np.linspace(0, 1, 9).reshape(3, 3)
# 顯示圖像數據
plt.imshow(a, interpolation = 'nearest', cmap = 'bone', origin = 'lower')
# 添加顏色條
plt.colorbar()
# 去掉坐標軸
plt.xticks(())
plt.yticks(())
plt.show()
10- 繪制3D圖形
# -*- coding: utf-8 -*-
"""
繪制3d圖形
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 定義figure
fig = plt.figure()
# 將figure變為3d
ax = Axes3D(fig)
# 數據數目
n = 256
# 定義x, y
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
# 生成網格數據
X, Y = np.meshgrid(x, y)
# 計算每個點對的長度
R = np.sqrt(X ** 2 + Y ** 2)
# 計算Z軸的高度
Z = np.sin(R)
# 繪制3D曲面
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('rainbow'))
# 繪制從3D曲面到底部的投影
ax.contour(X, Y, Z, zdim = 'z', offset = -2, cmap = 'rainbow')
# 設置z軸的維度
ax.set_zlim(-2, 2)
plt.show()
11- subplot繪制多圖
# -*- coding: utf-8 -*-
"""
subplot繪制多圖
"""
import matplotlib.pyplot as plt
plt.figure()
# 繪制第一個圖
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
# 繪制第二個圖
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 1])
# 繪制第三個圖
plt.subplot(2, 2, 3)
plt.plot([0, 1], [0, 1])
# 繪制第四個圖
plt.subplot(2, 2, 4)
plt.plot([0, 1], [0, 1])
plt.show()
# -*- coding: utf-8 -*-
"""
subplot繪制多圖
"""
import matplotlib.pyplot as plt
plt.figure()
# 繪制第一個圖
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# 繪制第二個圖
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 1])
# 繪制第三個圖
plt.subplot(2, 3, 5)
plt.plot([0, 1], [0, 1])
# 繪制第四個圖
plt.subplot(2, 3, 6)
plt.plot([0, 1], [0, 1])
plt.show()
12- figure繪制多圖
# -*- coding: utf-8 -*-
"""
figure繪制多圖
"""
# -*- coding: utf-8 -*-
"""
figure繪制多圖
"""
import matplotlib.pyplot as plt
# 定義figure
plt.figure()
# figure分成3行3列, 取得第一個子圖的句柄, 第一個子圖跨度為1行3列, 起點是表格(0, 0)
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan = 3, rowspan = 1)
ax1.plot([0, 1], [0, 1])
ax1.set_title('Test')
# figure分成3行3列, 取得第二個子圖的句柄, 第二個子圖跨度為1行3列, 起點是表格(1, 0)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan = 2, rowspan = 1)
ax2.plot([0, 1], [0, 1])
# figure分成3行3列, 取得第三個子圖的句柄, 第三個子圖跨度為1行1列, 起點是表格(1, 2)
ax3 = plt.subplot2grid((3, 3), (1, 2), colspan = 1, rowspan = 1)
ax3.plot([0, 1], [0, 1])
# figure分成3行3列, 取得第四個子圖的句柄, 第四個子圖跨度為1行3列, 起點是表格(2, 0)
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan = 3, rowspan = 1)
ax4.plot([0, 1], [0, 1])
plt.show()
或
# -*- coding: utf-8 -*-
"""
figure繪制多圖
"""
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# 定義figure
plt.figure()
# 分隔figure
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, 0:2])
ax3 = plt.subplot(gs[1, 2])
ax4 = plt.subplot(gs[2, :])
# 繪制圖像
ax1.plot([0, 1], [0, 1])
ax1.set_title('Test')
ax2.plot([0, 1], [0, 1])
ax3.plot([0, 1], [0, 1])
ax4.plot([0, 1], [0, 1])
plt.show()
13- figure圖的嵌套
# -*- coding: utf-8 -*-
"""
figure圖的嵌套
"""
import matplotlib.pyplot as plt
# 定義figure
fig = plt.figure()
# 定義數據
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# figure的百分比, 從figure 10%的位置開始繪制, 寬高是figure的80%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# 獲得繪制的句柄
ax1 = fig.add_axes([left, bottom, width, height])
# 繪制點(x,y)
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('test')
# 嵌套方法一
# figure的百分比, 從figure 10%的位置開始繪制, 寬高是figure的80%
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
# 獲得繪制的句柄
ax2 = fig.add_axes([left, bottom, width, height])
# 繪制點(x,y)
ax2.plot(x, y, 'r')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('part1')
# 嵌套方法二
plt.axes([bottom, left, width, height])
plt.plot(x, y, 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.title('part2')
plt.show()
14- 主次坐標軸
# -*- coding: utf-8 -*-
"""
主次坐標軸
"""
import numpy as np
import matplotlib.pyplot as plt
# 定義數據
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x ** 2
y2 = -1 * y1
# 定義figure
fig, ax1 = plt.subplots()
# 得到ax1的對稱軸ax2
ax2 = ax1.twinx()
# 繪制圖像
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b--')
# 設置label
ax1.set_xlabel('X data')
ax1.set_xlabel('Y1', color = 'g')
ax2.set_xlabel('Y2', color = 'b')
plt.show()
15- 創建動畫
# -*- coding: utf-8 -*-
"""
動畫
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
# 定義figure
fig, ax = plt.subplots()
# 定義數據
x = np.arange(0, 2 * np.pi, 0.01)
# line, 表示只取返回值中的第一個元素
line, = ax.plot(x, np.sin(x))
# 定義動畫的更新
def update(i):
line.set_ydata(np.sin(x + i/10))
return line,
# 定義動畫的初始值
def init():
line.set_ydata(np.sin(x))
return line,
# 創建動畫
ani = animation.FuncAnimation(fig = fig, func = update, init_func = init, interval = 10, blit = False, frames = 200)
# 展示動畫
plt.show()
# 動畫保存
#我這里是保存為html文件了,打開即可完美運行
ani.save('sin.html', writer = 'imagemagick', fps = 30, dpi = 100)