Python Matplotlib簡(jiǎn)易教程(小白教程)
簡(jiǎn)單演示
import matplotlib.pyplot as plt import numpy as np # 從[-1,1]中等距去50個(gè)數(shù)作為x的取值 x = np.linspace(-1, 1, 50) print(x) y = 2*x + 1 # 第一個(gè)是橫坐標(biāo)的值,第二個(gè)是縱坐標(biāo)的值 plt.plot(x, y) # 必要方法,用于將設(shè)置好的figure對(duì)象顯示出來 plt.show()

import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50) y = 2**x + 1 # 第一個(gè)是橫坐標(biāo)的值,第二個(gè)是縱坐標(biāo)的值 plt.plot(x, y) plt.show()

顯示多個(gè)圖像
import matplotlib.pyplot as plt
import numpy as np
# 多個(gè)figure
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
# 使用figure()函數(shù)重新申請(qǐng)一個(gè)figure對(duì)象
# 注意,每次調(diào)用figure的時(shí)候都會(huì)重新申請(qǐng)一個(gè)figure對(duì)象
plt.figure()
# 第一個(gè)是橫坐標(biāo)的值,第二個(gè)是縱坐標(biāo)的值
plt.plot(x, y1)
# 第一個(gè)參數(shù)表示的是編號(hào),第二個(gè)表示的是圖表的長(zhǎng)寬
plt.figure(num = 3, figsize=(8, 5))
# 當(dāng)我們需要在畫板中繪制兩條線的時(shí)候,可以使用下面的方法:
plt.plot(x, y2)
plt.plot(x, y1,
color='red', # 線顏色
linewidth=1.0, # 線寬
linestyle='--' # 線樣式
)
plt.show()
這里會(huì)顯示兩個(gè)圖像:


去除邊框,指定軸的名稱
import matplotlib.pyplot as plt
import numpy as np
# 從[-1,1]中等距去50個(gè)數(shù)作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
# 請(qǐng)求一個(gè)新的figure對(duì)象
plt.figure()
# 第一個(gè)是橫坐標(biāo)的值,第二個(gè)是縱坐標(biāo)的值
plt.plot(x, y1)
# 設(shè)置軸線的lable(標(biāo)簽)
plt.xlabel("I am x")
plt.ylabel("I am y")
plt.show()

同時(shí)繪制多條曲線
import matplotlib.pyplot as plt
import numpy as np
# 從[-1,1]中等距去50個(gè)數(shù)作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
# num表示的是編號(hào),figsize表示的是圖表的長(zhǎng)寬
plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
# 設(shè)置線條的樣式
plt.plot(x, y1,
color='red', # 線條的顏色
linewidth=1.0, # 線條的粗細(xì)
linestyle='--' # 線條的樣式
)
# 設(shè)置取值參數(shù)范圍
plt.xlim((-1, 2)) # x參數(shù)范圍
plt.ylim((1, 3)) # y參數(shù)范圍
# 設(shè)置點(diǎn)的位置
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
# 為點(diǎn)的位置設(shè)置對(duì)應(yīng)的文字。
# 第一個(gè)參數(shù)是點(diǎn)的位置,第二個(gè)參數(shù)是點(diǎn)的文字提示。
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$readly\ good$'])
# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 綁定x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()

多條曲線之曲線說明
import matplotlib.pyplot as plt
import numpy as np
# 從[-1,1]中等距去50個(gè)數(shù)作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
# 第一個(gè)參數(shù)表示的是編號(hào),第二個(gè)表示的是圖表的長(zhǎng)寬
plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# 設(shè)置取值參數(shù)
plt.xlim((-1, 2))
plt.ylim((1, 3))
# 設(shè)置lable
plt.xlabel("I am x")
plt.ylabel("I am y")
# 設(shè)置點(diǎn)的位置
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22,3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$readly\ good$'])
l1, = plt.plot(x, y2,
label='aaa'
)
l2, = plt.plot(x, y1,
color='red', # 線條顏色
linewidth = 1.0, # 線條寬度
linestyle='-.', # 線條樣式
label='bbb' #標(biāo)簽
)
# 使用legend繪制多條曲線
plt.legend(handles=[l1, l2],
labels = ['aaa', 'bbb'],
loc = 'best'
)
plt.show()

多個(gè)figure,并加上特殊點(diǎn)注釋
import matplotlib.pyplot as plt
import numpy as np
# 從[-1,1]中等距去50個(gè)數(shù)作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
plt.figure(figsize=(12, 8)) # 第一個(gè)參數(shù)表示的是編號(hào),第二個(gè)表示的是圖表的長(zhǎng)寬
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 綁定x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 顯示交叉點(diǎn)
x0 = 1
y0 = 2*x0 + 1
# s表示點(diǎn)的大小,默認(rèn)rcParams['lines.markersize']**2
plt.scatter(x0, y0, s = 66, color = 'b')
# 定義線的范圍,X的范圍是定值,y的范圍是從y0到0的位置
# lw的意思是linewidth,線寬
plt.plot([x0, x0], [y0, 0], 'k-.', lw= 2.5)
# 設(shè)置關(guān)鍵位置的提示信息
plt.annotate(r'$2x+1=%s$' %
y0,
xy=(x0, y0),
xycoords='data',
xytext=(+30, -30),
textcoords='offset points',
fontsize=16, # 這里設(shè)置的是字體的大小
# 這里設(shè)置的是箭頭和箭頭的弧度
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2')
)
# 在figure中顯示文字信息
# 可以使用\來輸出特殊的字符\mu\ \sigma\ \alpha
plt.text(0, 3,
r'$This\ is\ a\ good\ idea.\ \mu\ \sigma_i\ \alpha_t$',
fontdict={'size':16,'color':'r'})
plt.show()

tick能見度設(shè)置
import matplotlib.pyplot as plt
import numpy as np
# 從[-1,1]中等距去50個(gè)數(shù)作為x的取值
x = np.linspace(-1, 1, 50)
y = 2*x - 1
plt.figure(figsize=(12, 8)) # 第一個(gè)參數(shù)表示的是編號(hào),第二個(gè)表示的是圖表的長(zhǎng)寬
# alpha是設(shè)置透明度的
plt.plot(x, y, color='r', linewidth=10.0, alpha=0.5)
# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 綁定x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 可以使用tick設(shè)置透明度
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='y', edgecolor='None', alpha=0.7))
plt.show()

多條曲線通用例子
def init_colors():
return ['blue', 'red', 'green', 'black', 'pink', 'purple', 'gray', 'yellow']
def show_graph(data, save_png_name=None, colors=init_colors()):
"""
繪制折線圖
:param data: 數(shù)據(jù)格式:{label:{X:Y}, label:{X:Y}...}
:param save_png_name:保存的圖片的名字
:param colors: 顏色列表
:return:
None
"""
# 解決中文顯示亂碼的問題,不用中文就不需要設(shè)置了
my_font = font_manager.FontProperties(fname="/自己補(bǔ)充路徑/IOS8.ttf")
plt.figure(figsize=(14, 6))
plts = []
labels = []
for index, label in enumerate(data.keys()):
if label is 'rotate':
continue
color = colors[index]
X = data.get(label).keys()
Y = [data.get(label).get(x) for x in X]
temp, = plt.plot(X, Y, color=color, label=label)
plts.append(temp)
labels.append(label)
plt.legend(handles=plts, labels=labels, prop=my_font)
plt.show()
if save_png_name is not None:
plt.savefig(save_png_name)


散點(diǎn)圖
import matplotlib.pyplot as plt import numpy as np n = 1024 # 從[0] X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) T = np.arctan2(X, Y) plt.scatter(np.arange(5), np.arange(5)) plt.xticks(()) plt.yticks(()) plt.show()

條形圖
import matplotlib.pyplot as plt import numpy as np n = 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.figure(figsize=(12, 8)) 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 alignment水平方向 # va: vertical alignment垂直方向 plt.text(x, y+0.05, '%.2f' % y, ha='center', va='bottom') for x, y in zip(X,-Y2): # ha: horizontal alignment水平方向 # va: vertical alignment垂直方向 plt.text(x, y-0.05, '%.2f' % y, ha='center', va='top') # 定義范圍和標(biāo)簽 plt.xlim(-.5, n) plt.xticks(()) plt.ylim(-1.25, 1.25) plt.yticks(()) plt.show()

contour等高線圖
import matplotlib.pyplot as plt import numpy as np def get_height(x, y): # the height function return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2) n = 256 x = np.linspace(-3, 3, n) y = np.linspace(-3, 3, n) X, Y = np.meshgrid(x, y) plt.figure(figsize=(14, 8)) # use plt.contourf to filling contours # X, Y and value for (X, Y) point # 橫坐標(biāo)、縱坐標(biāo)、高度、 、透明度、cmap是顏色對(duì)應(yīng)表 # 等高線的填充顏色 plt.contourf(X, Y, get_height(X, Y), 16, alpah=0.7, cmap=plt.cm.hot) # use plt.contour to add contour lines # 這里是等高線的線 C = plt.contour(X, Y, get_height(X, Y), 16, color='black', linewidth=.5) # adding label plt.clabel(C, inline=True, fontsize=16) plt.xticks(()) plt.yticks(()) plt.show()

image圖片顯示
import matplotlib.pyplot as plt
import numpy as np
# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
"""
for the value of "interpolation", check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of "origin"= ['upper', 'lower'], check this:
http://matplotlib.org/examples/pylab_examples/image_origin.html
"""
# 這是顏色的標(biāo)注
# 主要使用imshow來顯示圖片,這里暫時(shí)不適用圖片來顯示,采用色塊的方式演示。
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.90) # 這是顏色深度的標(biāo)注,shrink表示壓縮比例
plt.xticks(())
plt.yticks(())
plt.show()

3D數(shù)據(jù)圖
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(12, 8))
ax = Axes3D(fig)
# 生成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)
# height value
Z = np.sin(R)
# 繪圖
# rstride(row)和cstride(column)表示的是行列的跨度
ax.plot_surface(X, Y, Z,
rstride=1, # 行的跨度
cstride=1, # 列的跨度
cmap=plt.get_cmap('rainbow') # 顏色映射樣式設(shè)置
)
# offset 表示距離zdir的軸距離
ax.contourf(X, Y, Z, zdir='z', offest=-2, cmap='rainbow')
ax.set_zlim(-2, 2)
plt.show()

Subplot多合一顯示
import matplotlib.pyplot as plt import numpy as np plt.figure() # 將整個(gè)figure分成兩行兩列 plt.subplot(2, 2, 1) # 第一個(gè)參數(shù)表示X的范圍,第二個(gè)是y的范圍 plt.plot([0, 1], [0, 1]) plt.subplot(222) plt.plot([0, 1], [0, 2]) plt.subplot(223) plt.plot([0, 1], [0, 3]) plt.subplot(224) plt.plot([0, 1], [0, 4]) plt.show()

分格顯示
subplot2grid
import matplotlib.pyplot as plt import numpy as np import matplotlib.gridspec as gridspec plt.figure() # 第一個(gè)元素表示將總的面板進(jìn)行劃分,劃分為3行3列, # 第二個(gè)元素表示該面板從0行0列開始,列的跨度(colspan)為3列,行的跨度(rowspan)為1 ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1) # 第一個(gè)元素的表示X的范圍為[1,2],第二個(gè)元素表示Y的范圍為[1,2] ax1.plot([1, 2], [1, 2]) ax1.set_title(r'$ax1\_title$') # 第一個(gè)元素表示將總的面板進(jìn)行劃分,劃分為3行3列, # 第二個(gè)元素表示該面板從1行0列開始,列的跨度(colspan)為2列,行的跨度(rowspan)取默認(rèn)值1 ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2) ax2.set_title(r'$ax2\_title$') # 第一個(gè)元素表示將總的面板進(jìn)行劃分,劃分為3行3列, # 第二個(gè)元素表示該面板從1行2列開始,行的跨度(rowspan)為2列,列的跨度(colspan)取默認(rèn)值1 ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) ax3.set_title(r'$ax3\_title$') # 第一個(gè)元素表示將總的面板進(jìn)行劃分,劃分為3行3列, # 第二個(gè)元素表示該面板從2行0列開始,行的跨度(rowspan)為2列,列的跨度(colspan)取默認(rèn)值1 ax4 = plt.subplot2grid((3, 3), (2, 0)) ax4.set_title(r'$ax4\_title$') # 第一個(gè)元素表示將總的面板進(jìn)行劃分,劃分為3行3列, # 第二個(gè)元素表示該面板從2行1列開始,行的跨度(rowspan)為2列,列的跨度(colspan)取默認(rèn)值1 ax5 = plt.subplot2grid((3, 3), (2, 1)) ax5.set_title(r'$ax5\_title$') plt.tight_layout() plt.show()

gridspec
import matplotlib.pyplot as plt import numpy as np plt.figure() # 首先,定義網(wǎng)格的布局為3行3列 gs = gridspec.GridSpec(3, 3) # 這里表示從0行全部都是ax1的 ax1 = plt.subplot(gs[0, :]) ax1.set_title(r'$ax1\_title$') # 這里表示第一行中0列和1列都是ax2的 ax2 = plt.subplot(gs[1, :2]) ax2.set_title(r'$ax2\_title$') # 這里表示第一行中2列是ax3的 ax3 = plt.subplot(gs[1:, 2]) ax3.set_title(r'$ax3\_title$') # 這里表示最后一行中0列是ax4的 ax4 = plt.subplot(gs[-1, 0]) ax4.set_title(r'$ax4\_title$') # 這里表示最后一行中倒數(shù)第二列是ax5的 ax5 = plt.subplot(gs[-1, -2]) ax5.set_title(r'$ax5\_title$') plt.tight_layout() plt.show()

easy to define structure分格顯示
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
# sharex表示共享X軸,sharey表示共享y軸
f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
# 顯示點(diǎn)(1, 2), (1, 2)
ax11.scatter([1, 2], [1, 2])
ax11.set_title('11')
ax12.set_title('11')
ax21.set_title('21')
ax22.set_title('22')
plt.tight_layout()
plt.show()

圖中圖
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 6))
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# 大圖
left, bottom, width, weight = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, weight])
ax1.plot(x, y, 'r')
ax1.set_xlabel(r'$x$')
ax1.set_ylabel(r'$y$')
ax1.set_title(r'$××Interesting××$')
# 左上小圖
left, bottom, width, weight = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, weight])
ax2.plot(y, x, 'b')
ax2.set_xlabel(r'$x$')
ax2.set_ylabel(r'$y$')
ax2.set_title(r'$title\ inside\ 1$')
# 右下小圖
plt.axes([0.6, 0.2, 0.25, 0.25])
# 將y的數(shù)據(jù)逆序輸出[::1]
plt.plot(y[::-1],x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title(r'$title\ inside\ 2$')
plt.show()

主次坐標(biāo)軸
import matplotlib.pyplot as plt import numpy as np # 從[0, 10]以0.1為間隔,形成一個(gè)列表 x = np.arange(0, 10, 0.1) y1 = 0.05 * x**2 y2 = -1 * y1 fig, ax1 = plt.subplots() # 鏡像(上下左右顛倒) ax2 = ax1.twinx() ax1.plot(x, y1, 'g-') ax2.plot(x, y2, 'b--') # 為軸進(jìn)行命名 ax1.set_xlabel(r'$X\ data$', fontsize=16) ax1.set_ylabel(r'$Y1$', color='g', fontsize=16) ax2.set_ylabel(r'$Y2$', color='b', fontsize=16) plt.show()

Animation動(dòng)畫
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
fig, ax = plt.subplots()
# 從[0, 2*np.pi]以0.01為間隔,形成一個(gè)列表
x = np.arange(0, 2*np.pi, 0.01)
# 這里只需要列表的第一個(gè)元素,所以就用逗號(hào)“,”加空白的形式省略了列表后面的元素
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/100))
return line,
def init():
line.set_ydata(np.sin(x))
# 這里由于僅僅需要列表的第一個(gè)參數(shù),所以后面的就直接用空白省略了
return line,
ani = animation.FuncAnimation(fig=fig,
func=animate, # 動(dòng)畫函數(shù)
frames=100, # 幀數(shù)
init_func=init, # 初始化函數(shù)
interval=20, # 20ms
blit=True)
plt.show()

到此這篇關(guān)于Python Matplotlib簡(jiǎn)易教程(小白教程)的文章就介紹到這了,更多相關(guān)Python Matplotlib簡(jiǎn)易教程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Python進(jìn)行微服務(wù)架構(gòu)的監(jiān)控與日志分析
Python作為一種強(qiáng)大的編程語言,提供了豐富的工具和庫,可以幫助我們實(shí)現(xiàn)對(duì)微服務(wù)架構(gòu)的監(jiān)控和日志分析,本文將介紹如何利用Python編寫監(jiān)控腳本和日志分析程序,以便于更好地管理和維護(hù)微服務(wù)系統(tǒng)2024-03-03
python 解決數(shù)據(jù)庫寫入時(shí)float自動(dòng)變?yōu)檎麛?shù)的問題
這篇文章主要介紹了python 解決數(shù)據(jù)庫寫入時(shí)float自動(dòng)變?yōu)檎麛?shù)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
簡(jiǎn)述python四種分詞工具,盤點(diǎn)哪個(gè)更好用?
這篇文章主要介紹了python四種分詞工具的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
使用python 3實(shí)現(xiàn)發(fā)送郵件功能
本文通過實(shí)例代碼給大家介紹了使用python 3實(shí)現(xiàn)發(fā)送郵件功能,代碼簡(jiǎn)單易懂非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06
python如何獲取網(wǎng)絡(luò)數(shù)據(jù)
這篇文章主要介紹了python如何獲取網(wǎng)絡(luò)數(shù)據(jù),幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
Pytorch中使用ImageFolder讀取數(shù)據(jù)集時(shí)忽略特定文件
這篇文章主要介紹了Pytorch中使用ImageFolder讀取數(shù)據(jù)集時(shí)忽略特定文件,具有一的參考價(jià)值需要的小伙伴可以參考一下,希望對(duì)你有所幫助2022-03-03
python中關(guān)于eval函數(shù)的使用及說明
這篇文章主要介紹了python中關(guān)于eval函數(shù)的使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
WINDOWS 同時(shí)安裝 python2 python3 后 pip 錯(cuò)誤的解決方法
這篇文章主要給大家分享的是在WINDOWS下同時(shí)安裝 python2 python3 后 pip 錯(cuò)誤的解決方法,非常的實(shí)用,有需要的小伙伴可以參考下2017-03-03
19個(gè)Python?Sklearn中超實(shí)用的隱藏功能分享
今天跟大家介紹?19?個(gè)?Sklearn?中超級(jí)實(shí)用的隱藏的功能,這些功能雖然不常見,但非常實(shí)用,它們可以直接優(yōu)雅地替代手動(dòng)執(zhí)行的常見操作2022-07-07

