
import包:
matplotlib包含有很多的模塊,在具體使用的時候根據(jù)需要導(dǎo)入依賴的模塊。通過將matplotlib包導(dǎo)入重命名為“mpl”,pyplot模塊命名為“plt”,其中ticker為坐標(biāo)軸刻度相關(guān)的模塊。最基本的導(dǎo)入pyplot包即可。其他的包的使用在后續(xù)使用的時候逐一進(jìn)行說明。
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
全局配置:
#設(shè)定坐標(biāo)洗名稱title,圖例legend,坐標(biāo)軸名稱,刻度標(biāo)簽的字體大小,畫布大小
large = 22; med = 16; small = 12
params = {'axes.titlesize': large,
'legend.fontsize': med,
'figure.figsize': (16, 10),
'axes.labelsize': med,
'axes.titlesize': med,
'xtick.labelsize': med,
'ytick.labelsize': med,
'figure.titlesize': large}
#統(tǒng)一通過plt.rcParams設(shè)置
plt.rcParams.update(params)
#設(shè)置圖的樣式
plt.style.use('seaborn-whitegrid')
#設(shè)置中文字體
mpl.rcParams['font.family'] = ['Heiti TC']
# matplotlib具體作用是當(dāng)調(diào)用matplotlib.pyplot的繪圖函數(shù)plot()進(jìn)行繪圖的時候,或者生成一個figure畫布的時候,可以直接在你的python console里面生成圖像
%matplotlib inline
創(chuàng)建畫布 figure
- 顯示創(chuàng)建畫布
通過plt.figure()顯示的創(chuàng)建畫布,然后往畫布中添加對應(yīng)的坐標(biāo)系
# 顯示創(chuàng)建一個figure對象
figure = plt.figure()
#為創(chuàng)建的figer添加不同的坐標(biāo)系,前兩個參數(shù)2,1表明坐標(biāo)系為2行1列的排版,最后一個參數(shù)表明為那個坐標(biāo)系
axes1 = figure.add_subplot(2,1,1)
axes2 = figure.add_subplot(2,1,2)
輸出如下:

- 隱式創(chuàng)建畫布:
在執(zhí)行plot()的時候首先會創(chuàng)建畫布figure,在畫布自動添加一個坐標(biāo)系axes,然后根據(jù)plot()中的數(shù)據(jù)繪制對應(yīng)的圖像;
x = [1,2,3,4]
y = [2,4,6,8]
plt.plot(x,y)
plt.show()
輸出如下:

在隱式創(chuàng)建的時候不需要關(guān)心畫布和坐標(biāo)系。隱式創(chuàng)建畫布的時候,一個figure對象上,只能有一個axes坐標(biāo)系,因此只能繪制一個圖形。
plot函數(shù)使用:
函數(shù)
通常plot()函數(shù)有如下兩種參數(shù)的調(diào)用形式:
plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
參數(shù):
- x: x軸數(shù)據(jù)
- y: y軸數(shù)據(jù)
- fmt:fmt='[marker][line][color]' 表明圖表的基本屬性: 顏色(color)、點(diǎn)型(marker)、線型(linestyle)
- data:可索引的數(shù)據(jù),類似dataframe對象,可選參數(shù)
- kwargs:指定透明度,線條的寬度,標(biāo)簽等等一系列的參數(shù)
具體詳可以在官網(wǎng)中查詢:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html?highlight=plot#matplotlib.pyplot.plot
除了plot函數(shù)外,針對不同的圖形有專門的函數(shù)進(jìn)行繪制。具體在后面會逐個進(jìn)行介紹。
坐標(biāo)軸范圍
同時設(shè)定x,y兩軸的范圍
- 函數(shù)
plt.axis([xmin, xmax, ymin, ymax]) - 示例
# 導(dǎo)入模塊
import matplotlib.pyplot as plt
import numpy as np
# 生成數(shù)據(jù)
x = np.linspace(-8, 8, 80)
y = x*3
plt.plot(x, y)
# 設(shè)置軸的范圍
plt.axis([-5, 5, -20, 20])
plt.show()
輸出如下:

分別設(shè)置兩軸的范圍
- 函數(shù):
- xlim(*args, **kwargs)
設(shè)置和獲取對應(yīng)坐標(biāo)軸的范圍
- xlim(*args, **kwargs)
left, right = xlim() # return the current xlim
xlim((left, right)) # set the xlim to left, right
xlim(left, right) # set the xlim to left, right
等價于坐標(biāo)系設(shè)定set_xlim()
axes.set_xlim(left, right)
- ylim(*args, **kwargs)
設(shè)置和獲取對應(yīng)坐標(biāo)軸的范圍
bottom, top = ylim() # return the current ylim
ylim((bottom, top)) # set the ylim to bottom, top
ylim(bottom, top) # set the ylim to bottom, top
等價于坐標(biāo)系設(shè)定set_ylim()
axes.set_ylim(bottom, top)
- 示例:
# 導(dǎo)入模塊
import matplotlib.pyplot as plt
import numpy as np
# 生成數(shù)據(jù)
x = np.linspace(-8, 8, 80)
y = x*3
plt.plot(x, y)
# 設(shè)置軸的范圍
plt.xlim(-5,5)
plt.ylim(-16,16)
plt.show()
輸出如下:

刻度設(shè)置:
普通刻度
- 函數(shù):
x軸的刻度:plt.xticks(item)
y軸的刻度:plt.yticks(item) - 示例:
# 導(dǎo)入模塊
import matplotlib.pyplot as plt
import numpy as np
# 生成數(shù)據(jù)
x = np.linspace(-8, 8, 80)
y = x*3
plt.plot(x, y)
# 設(shè)置軸的范圍
plt.xticks(np.arange(-5,5,1))
plt.yticks([-15,-5,3,9,15])
plt.show()
輸出如下:

添加文本的刻度
plt.xticks(['數(shù)據(jù)'], ["標(biāo)簽"]) 設(shè)置刻度的基礎(chǔ)上,在添加一個列表,來顯示刻度
主次刻度設(shè)置
需要導(dǎo)入:from matplotlib.ticker import MultipleLocator, FormatStrFormatter
- 主刻度:(x,y軸相同)
倍數(shù):ax.xaxis.set_major_locator(MultipleLocator(倍數(shù)))
文本格式:ax.xaxis.set_major_formatter(FormatStrFormatter('%占位數(shù).小數(shù)點(diǎn)數(shù)f')) - 副刻度:(x,y軸相同,將"major"改為"minor"即可)
倍數(shù):ax.xaxis.set_minor_locator(MultipleLocator(倍數(shù)))
文本格式:ax.xaxis.set_minor_formatter(FormatStrFormatter('%占位數(shù).小數(shù)點(diǎn)數(shù)f'))
# 導(dǎo)入模塊
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
'''
生成數(shù)據(jù)
'''
x = np.linspace(-40, 40)
y = x*3
plt.plot(x, y)
ax = plt.gca()
'''
設(shè)置軸的主刻度
'''
ax.xaxis.set_major_locator(MultipleLocator(20)) # 設(shè)置20倍數(shù)
ax.xaxis.set_major_formatter(FormatStrFormatter('%2.1f')) # 設(shè)置文本格式
ax.yaxis.set_major_locator(MultipleLocator(50)) # 設(shè)置50倍數(shù)
ax.yaxis.set_major_formatter(FormatStrFormatter('%2.2f')) # 設(shè)置文本格式
'''
設(shè)置軸的副刻度
'''
ax.xaxis.set_minor_locator(MultipleLocator(10)) # 設(shè)置10倍數(shù)
ax.xaxis.set_minor_formatter(FormatStrFormatter('%2.1f')) # 設(shè)置文本格式
ax.yaxis.set_minor_locator(MultipleLocator(25)) # 設(shè)置25倍數(shù)
ax.yaxis.set_minor_formatter(FormatStrFormatter('%1.0f')) # 設(shè)置文本格式
ax.tick_params(which='minor', width=1, labelsize=10,bottom=True)
ax.tick_params(which='minor', length=2, labelsize=10, labelcolor='0.25')
plt.show()
輸出如下:

圖例
在plot()的時候增加labe添加文本內(nèi)容,通過legend()顯示出來。
示例:
import matplotlib.pyplot as plt
import numpy as np
'''
生成數(shù)據(jù)
'''
x = np.linspace(-8, 8, 80)
y = x*3
plt.plot(x, y,label="x*3")
plt.plot(x, y*1.5,label="x*4.5")
'''
loc 設(shè)定legend的位置
'''
plt.legend(loc='lower right')
plt.show()
輸出如下:

spines設(shè)置
- 屬性:
| 函數(shù) | 說明 | 默認(rèn)值 |
|---|---|---|
| set_visible(bool) | 邊框的可見性 | True |
| ax.xaxis.set_ticks_position({"top","left"……}) | 刻度的顯示位置 | 外面(不是ax.spines[' '].) |
| set_position({"top","left"……}) | 邊框的位置 | 左下角為交點(diǎn) |
| set_color(string) | 邊框的顏色 | “black"(當(dāng)值為None也是隱藏) |
| set_linewidth(int) | 邊框的寬度 | 1 |
| set_linestyle(string) | 邊框的線性 | ”-“ |
- 箭頭
導(dǎo)入axisartist
import mpl_toolkits.axisartist as axisartist
1、隱藏原有的邊框坐標(biāo)系
2、創(chuàng)建新的坐標(biāo)系,添加箭頭
3、創(chuàng)建新的坐標(biāo)系時ax.new_floating_axis(0, 0)第一個參數(shù):0表示橫線,1表示豎線,第二個參數(shù):表示經(jīng)過那個坐標(biāo)點(diǎn)。
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.axisartist as axisartist
# 生成數(shù)據(jù)
x = np.linspace(-10, 10, 80)
y = x*3
plt.plot(x, y)
ax = plt.gca()
'''
使用ax.spines[]選定邊框,使用set_color()將選定的邊框的顏色設(shè)為 none
'''
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
'''
移動坐標(biāo)軸,將bottom即x坐標(biāo)軸移動到y(tǒng)=0的位置
ax.xaixs為x軸,set_ticks_position()用于從上下左右(top/bottom/left/right)四條脊柱中選擇一個作為x軸
使用set_position()設(shè)置邊框位置:y=0的位置。位置的所有屬性包括:outward、axes、data
'''
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
'''
將left 即y坐標(biāo)軸設(shè)置到x=0的位置
'''
ax.yaxis.set_ticks_position('left') # 選定y軸
ax.spines['left'].set_position(('data', 0))
'''
不顯示網(wǎng)格
'''
plt.grid( None)
plt.show()
輸出如下:

多圖的處理
- subplot()
plt.subplot(m,n,p)m和n代表在一個圖像窗口中顯示m行n列個圖像,也就是整個figure中有n個圖是排成一行的,一共m行,后面的p代表現(xiàn)在選定第p個圖像區(qū)域,即在第p個區(qū)域作圖
另外一種多圖顯示的方式參見 matplotlib可視化之直方圖 擴(kuò)展部分中的雙變量直方圖
import matplotlib.pyplot as plt
fig=plt.figure()
'''
子圖1 第1行第1列
'''
ax1=fig.add_subplot(221) #2*2的圖形 在第一個位置
ax1.text(0.5,0.5, 'one',ha='center',va='center',size=20,alpha=.5)
'''
子圖2 第1行第2列
'''
ax2=fig.add_subplot(222)
ax2.text(0.5,0.5, 'one',ha='center',va='center',size=20,alpha=.5)
'''
子圖3 第2行第1列
'''
ax3=fig.add_subplot(223)
ax3.text(0.5,0.5, 'one',ha='center',va='center',size=20,alpha=.5)
'''
子圖4 第2行第2列
'''
ax4=fig.add_subplot(224)
ax4.text(0.5,0.5, 'one',ha='center',va='center',size=20,alpha=.5)
plt.show()
輸出如下:

常用的對象:
- figure 畫布
- axes 坐標(biāo)系,一個畫布上可以有多個坐標(biāo)系
- axis 坐標(biāo)軸,一個坐標(biāo)系中可以有多個坐標(biāo)軸,一般都是二維平面坐標(biāo)系,或者三維立體坐標(biāo)系
- title 標(biāo)題
- legend 圖例
- grid 背景網(wǎng)格
- tick 刻度
- axis label 坐標(biāo)軸名稱
- tick label 刻度名稱
- major tick label 主刻度標(biāo)簽
- minor tick label 副刻度標(biāo)簽
- line 線
- style 線條樣式
- marker 點(diǎn)標(biāo)記
- font 字體相關(guān)