一文了解python作图(matplotlib.pyplot)
參考視頻:為什么用 Matplotlib
視頻總時(shí)長兩個(gè)多小時(shí),可以整體看一遍,然后看這個(gè)就會(huì)很清楚
文章目錄
- 1. 基本用法
- 1.1 基礎(chǔ)作圖
- 1.2 figure圖像
- 1.3 設(shè)置坐標(biāo)軸
- 1.3.1 基本設(shè)置
- 1.3.2 使用Latex公式
- 1.3.3 設(shè)置坐標(biāo)軸位置
- 1.4 legend圖例
- 1.4.1 基礎(chǔ)使用
- 1.4.2 設(shè)置圖例位置
- 1.4.3 指定顯示某幾條線并設(shè)置新名稱
- 1.5 annotation 注解
- 1.6 設(shè)置tick可見度
- 2 數(shù)據(jù)呈現(xiàn)
- 2.1 散點(diǎn)圖
- 2.2 條形圖
- 2.3 等高線圖
- 2.4 使用圖片
- 2.5 3D數(shù)據(jù)
- 3. Subplot多合一顯示
- 3.1 plt.subplot
- 3.2 plt.subplot2grid
- 3.3 gridspec.GridSpec
- 3.4 plt.subplots
- 4. 其他
- 4.1 圖中圖
- 4.2 次坐標(biāo)軸
- 4.3 動(dòng)畫 animation
1. 基本用法
1.1 基礎(chǔ)作圖
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-1, 1, 50) y = x * x + 1 plt.plot(x, y) plt.show()1.2 figure圖像
在不同的figure中展示不同的圖片,在每次繪圖前指定plt.figure()即可繪制到不同figure中,其中可以指定figure的序號(hào)
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-1, 1, 50) y1 = x * x + 1 y2 = 2 * xplt.figure(num=1) plt.plot(x, y1)plt.figure(num=2, figsize=(8, 5)) plt.plot(x, y2) plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--') plt.show()figure1:
figure2:
1.3 設(shè)置坐標(biāo)軸
1.3.1 基本設(shè)置
- plt.xlim(xleft, xright):設(shè)置x軸顯示范圍
- plt.ylim(ylow, yhigh):設(shè)置y軸的顯示范圍
- plt.xlabel(description):設(shè)置x軸描述
- plt.ylabel(description):設(shè)置y軸描述
- plt.xticks([1,2,3,4,5]):設(shè)置x軸標(biāo)簽
- plt.yticks([1,2,3,4,5]):設(shè)置y軸標(biāo)簽
- plt.yticks([1,2,3], ['one','two','three]):設(shè)置對(duì)應(yīng)標(biāo)簽位置文字
- plt.xlabel(r'$axis x description \alpha$'):使用latex公式
1.3.2 使用Latex公式
其中文字部分也可以使用latex公式進(jìn)行描述,例如設(shè)置某個(gè)label為 g o o d β good\ \beta good?β
# 設(shè)置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])1.3.3 設(shè)置坐標(biāo)軸位置
首先去掉右邊和上邊兩個(gè)邊框,然后設(shè)置x軸為下邊框,y軸為上邊框,最后設(shè)置邊框位置即可
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * xplt.plot(x, y2) plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--')# 設(shè)置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設(shè)置x,y軸的坐標(biāo)軸描述 plt.xlabel(r'$axis x description$', loc="right") plt.ylabel('axis y description', loc='top')# 設(shè)置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設(shè)置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])# gca: get current axis ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))plt.show()1.4 legend圖例
1.4.1 基礎(chǔ)使用
通過給每一個(gè)plot出來的圖像添加label屬性,然后調(diào)用plt.legend()即可顯示圖例
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * x# 設(shè)置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設(shè)置x,y軸的坐標(biāo)軸描述 plt.xlabel(r'$axis x description$') plt.ylabel('axis y description')# 設(shè)置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設(shè)置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])plt.plot(x, y2, label='up') plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--', label='down') plt.legend()plt.show()1.4.2 設(shè)置圖例位置
支持的位置屬性:'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'
best是根據(jù)線的顯示位置尋找最優(yōu)的顯示地方
通過調(diào)用plt.legend(loc='')指定loc屬性即可
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * x# 設(shè)置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設(shè)置x,y軸的坐標(biāo)軸描述 plt.xlabel(r'$axis x description$') plt.ylabel('axis y description')# 設(shè)置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設(shè)置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])plt.plot(x, y2, label='up') plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--', label='down') plt.legend(loc="upper right")plt.show()1.4.3 指定顯示某幾條線并設(shè)置新名稱
雖然繪制了兩條線,但是通過handles屬性可以指定繪制某幾條線,同時(shí)也可以設(shè)置各線的先后位置,另外還可以通過labels指定新的圖例名稱
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * x# 設(shè)置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設(shè)置x,y軸的坐標(biāo)軸描述 plt.xlabel(r'$axis x description$') plt.ylabel('axis y description')# 設(shè)置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設(shè)置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])l1, = plt.plot(x, y2, label='up') l2, = plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--', label='down') plt.legend(handles=[l1], labels=['aaa'], loc="upper right")plt.show()1.5 annotation 注解
通過plt.annotation()和plt.text()為圖象添加注解
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = 2 * x + 1plt.figure(figsize=(8, 5)) plt.plot(x, y1)# gca: get current axis ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))x0 = 1 y0 = 2 * x0 + 1 plt.scatter(x0, y0, s=50, color='b') plt.plot([x0, x0], [0, y0], 'k--', linewidth=2)plt.annotate(r"$2x+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"$This\ is\ annotation.\ \mu\ \sigma_i $", fontdict={'size': 16, "color": 'r'}) plt.show()1.6 設(shè)置tick可見度
有時(shí)候線會(huì)把標(biāo)簽壓住,此時(shí)可以通過設(shè)置標(biāo)簽的zorder屬性來制定覆蓋順序
zorder用來控制繪圖的順序,也就是所謂的疊加樣式。zorder越大,相當(dāng)于畫上去的越晚,也就在上面了。
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y2 = 0.1 * xplt.plot(x, y2, linewidth=10, zorder=1) plt.ylim(-2, 2) # gca: get current axis ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))for label in ax.get_xticklabels() + ax.get_yticklabels():label.set_zorder(2)label.set_fontsize(12)label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.7))plt.show()2 數(shù)據(jù)呈現(xiàn)
2.1 散點(diǎn)圖
通過plt.scatter()生成散點(diǎn)圖
import matplotlib.pyplot as plt import numpy as npn = 1024X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) T = np.arctan2(Y, X)plt.scatter(X, Y, s=75, c=T, alpha=.5)plt.xlim(-1.5, 1.5) plt.ylim(-1.5, 1.5)plt.xticks([]) plt.yticks([]) plt.show()生成一條斜線散點(diǎn)圖
import matplotlib.pyplot as plt import numpy as npplt.scatter(np.arange(5), np.arange(5))plt.show()2.2 條形圖
使用plt.bar()繪制條形圖
import matplotlib.pyplot as plt import numpy as npn = 12 X = np.arange(n) 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='#9999ff', edgecolor='white') plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')for x, y in zip(X, Y1):# ha: horizontal alignmentplt.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')for x, y in zip(X, Y2):# ha: horizontal alignmentplt.text(x, -y - 0.05, '%.2f' % y, ha='center', va='top')plt.xlim(-0.5, n) plt.xticks([]) plt.ylim(-1.25, 1.25) plt.yticks([])plt.show()2.3 等高線圖
- 使用plt.meshgrid()生成框格
- 使用plt.contourf()生成等高線填充圖
- 使用plt.contour()生成等高線
2.4 使用圖片
import matplotlib.pyplot as plt import numpy as npimg = np.random.uniform(0, 1000, 100).reshape((10, 10))plt.imshow(img, interpolation='nearest', origin='upper') plt.colorbar()plt.xticks([]) plt.yticks([]) plt.show()2.5 3D數(shù)據(jù)
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D# 生成3D figure fig = plt.figure() ax = Axes3D(fig, auto_add_to_figure=False) fig.add_axes(ax)# X, Y value 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 = np.sin(R)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), edgecolor='k') ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')ax.set_zlim(-2, 2) plt.show()3. Subplot多合一顯示
3.1 plt.subplot
使用plt.subplot(rownum, columnnum, index)說明新圖紙是幾行幾列的
import matplotlib.pyplot as pltplt.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, 1, 2) plt.plot([0, 1], [0, 1])plt.show()3.2 plt.subplot2grid
使用plt.subplot2grid(總格數(shù), 起始格數(shù), rowspan, colspan)來繪制
import matplotlib.pyplot as pltplt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1) ax1.plot([1, 2], [1, 2]) # 設(shè)置某屬性的時(shí)候需要在前面加set_ ax1.set_title("ax1 title")ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) ax4 = plt.subplot2grid((3, 3), (2, 0)) ax5 = plt.subplot2grid((3, 3), (2, 1))plt.tight_layout() plt.show()3.3 gridspec.GridSpec
首先使用gridspec.GridSpec(rownum, colnum)聲明將figure分割成幾塊,然后在繪圖時(shí)使用切片聲明使用哪幾塊即可
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspecplt.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[2, 0]) ax5 = plt.subplot(gs[2, 1])plt.tight_layout() plt.show()3.4 plt.subplots
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspecf, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True) ax11.plot([1, 2], [1, 2])plt.tight_layout() plt.show()4. 其他
4.1 圖中圖
通過指定在整個(gè)figure中的位置和大小來完成圖中圖的效果
- 方法一:通過fig.add_axes([left, bottom, width, height])來生成新的axes繪制
- 方法二:通過plt.axes([left, bottom, width, height])直接聲明接下來要繪制的圖形
4.2 次坐標(biāo)軸
在同一個(gè)圖中兩邊顯示不同的坐標(biāo)軸對(duì)應(yīng)不同的數(shù)據(jù)
import matplotlib.pyplot as plt import numpy as npx = np.arange(0, 10, 0.1) y1 = 0.05 * x ** 2 y2 = -1 * y1fig, ax1 = plt.subplots() ax2 = ax1.twinx()ax1.plot(x, y1, 'g-') ax2.plot(x, y2, 'b--')ax1.set_xlabel('X data') ax1.set_ylabel('Y1', color='g') ax2.set_ylabel('Y2', color='g')plt.show()4.3 動(dòng)畫 animation
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animationfig, ax = plt.subplots()x = np.arange(0, 2 * np.pi, 0.01) line, = ax.plot(x, np.sin(x))def animate(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=animate, frames=100, init_func=init, interval=20, blit=True)plt.show()總結(jié)
以上是生活随笔為你收集整理的一文了解python作图(matplotlib.pyplot)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电商技巧:如何整店商品图片下载并分类保存
- 下一篇: 好高的佣金,《新程序员》合伙人计划来袭,