python使用Matplotlib繪圖及設(shè)置實(shí)例(用python制圖)
# matplotlib提供快速繪圖模塊pyplot,它模仿了MATLAB的部分功能
import matplotlib.pyplot as plt? ? ? ? #導(dǎo)入繪圖模塊 from matplotlib import pyplot as plt? ? ? ? ? ?#兩種導(dǎo)入方法都可
第一節(jié)內(nèi)容的精簡(jiǎn)版總結(jié):
- 繪制折線(xiàn)圖(plt.plot)
- 設(shè)置圖片大小和分辨率(plt.figure)
- 保存圖片到本地(plt.savefig)
- 設(shè)置xy軸刻度和字符串(xticks、yticks)
- 設(shè)置標(biāo)題、xy軸標(biāo)簽(title、xlable、ylable)
- 設(shè)置字體(font_manager.fontProperties,matplotlib.rc)
- 同一張圖繪制多線(xiàn)條(plt多次plot)
- 添加圖例、繪制網(wǎng)格
- 其他圖像類(lèi)型(散點(diǎn)圖plt.scatter,條形圖plt.bar,橫向plt.barh,直方圖plt.hist(bin.width組距、num_bins分多少組、))
一、初識(shí)matplotlib.pyplot
準(zhǔn)備好制圖數(shù)據(jù),傳入?yún)?shù)。即可使用plt.plot(參數(shù))、plt.show()一鍵出圖!
import matplotlib.pyplot as plt x = [......] y = [......] plt.plot(x,y,label='圖例')? ? ? ? #繪圖,并且標(biāo)注圖例 plt.show()? ? ? ? #顯示 plot.legend(prop=my_font)? ? ? ? #設(shè)置顯示圖例,括號(hào)中意思為顯示中文(后面講解)
1.繪制圖像
plt.plot() 參數(shù)設(shè)置:
- color=’ ‘ 線(xiàn)條顏色
- linestyle=’‘ 線(xiàn)條風(fēng)格
- linewidth= 線(xiàn)條粗細(xì)
- alpha=0.5 透明度 (對(duì)照表見(jiàn)常見(jiàn)繪圖屬性設(shè)置附表)
一個(gè)實(shí)例:假設(shè)一天中每隔兩個(gè)小時(shí)(range(2,26,2))的氣溫(℃)分別是[15,13,14.5,17,20,25,26,26,27,22,18,15]
import matplotlib.pyplot as plt x = range(2,26,2) y = [15,13,14.5,17,20,25,26,26,27,22,18,15] # 繪圖 plt.plot(x,y) # 顯示 plt.show()
繪制出如下圖片:
2.設(shè)置圖片大小
在繪制圖片之前,使用plt.figure函數(shù)設(shè)置圖片大小,其中figsize為元組,分別代表長(zhǎng)寬,dpi(Dot Per Inch)為分辨率表示的單位之一。
plt.figure(figsize=(20,8),dpi=150) #圖片大小為20*8,每英寸150個(gè)像素點(diǎn)
3.保存圖片文件
plt.savefig("./t1.png") #將圖片保存到本地
引號(hào)里為文件路徑和文件名( ./ 代表當(dāng)前路徑,png為文件后綴/格式)
4.設(shè)置X,Y軸刻度范圍
設(shè)置x,y軸的范圍可以使用多種方法
plt.xticks(x)? ? ? ? # 將x里的值作為刻度 plt.xticks(range(2,25))? ? ? ? #傳入range數(shù)列 plt.yticks(range(min(y),max(y)+1))? ? ? ? #傳入最小到最大值數(shù)列
_xticks_lables = [i/2 for i in range(4,49)]? ? ? ? ? ? ? ? # 生成更復(fù)雜的數(shù)列 plt.xticks(_xticks_lables[::3])? ? ? ? #取步長(zhǎng)作為刻度
自定義刻度內(nèi)容
_x =list(x) [::3] _xticks_labels = ["10點(diǎn){ }分".format(i) for i in _x] plt.xticks(_x,_xticks_labels)? ? ? ? #分別代表刻度范圍和刻度內(nèi)容
5.添加描述信息(標(biāo)題、軸標(biāo)簽)
plt.title("折線(xiàn)圖") ? ?#設(shè)置標(biāo)題 plt.xlabel("時(shí)間") ? ?#設(shè)置x軸標(biāo)注 plt.ylabel("氣溫") ? ?#設(shè)置y軸標(biāo)注
6.設(shè)置顯示中文(導(dǎo)入字體模塊)
from matplotlib import font_manager????????#導(dǎo)入字體管理模塊 my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF") #定義中文字體屬性,文字儲(chǔ)存路徑可以在C:/WINDOWS/Fonts/找到,這里設(shè)置為宋體 plt.xlabel("時(shí)間",fontproperties = my_font,fontsize = 18) #在設(shè)置x坐標(biāo)中文標(biāo)注,令fontproperties = my_font,fontsize令字體為18號(hào) #plt.title,plt.ylabel,plt.xticks,plt.yticks設(shè)置中文標(biāo)注類(lèi)似
7.繪制網(wǎng)格
plt.grid(alpha=0.4)
繪制一個(gè)溫度隨時(shí)間變化的折線(xiàn)圖實(shí)例
import matplotlib.pyplot as plt import random #導(dǎo)入隨機(jī)生成模塊 from matplotlib import font_manager#導(dǎo)入字體管理模塊 my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF") #定義中文字體屬性,文字儲(chǔ)存路徑可以在C:/WINDOWS/Fonts/找到,本次設(shè)置為宋體 x = range(0,120) #x值為0-120 y = [random.randint(20,35) for i in range(120)] #y值為120個(gè)在20-35之間的隨機(jī)數(shù) plt.figure(figsize=(15,10),dpi = 80) #圖片大小為15*10,每英寸80個(gè)像素點(diǎn) '''調(diào)整x軸刻度''' _xticks_labels = ["10點(diǎn){}分".format(i) for i in range(60)] _xticks_labels += ["11點(diǎn){}分".format(i) for i in range(60,120)] plt.xticks(list(x)[::5],_xticks_labels[::5],rotation=45) #rotation旋轉(zhuǎn)度數(shù) #取步長(zhǎng)5,數(shù)字和字符串一一對(duì)應(yīng),保證數(shù)據(jù)的長(zhǎng)度一樣 '''設(shè)置標(biāo)注''' plt.title("10點(diǎn)到12點(diǎn)每分鐘溫度變化圖",fontproperties = my_font,fontsize = 24) #設(shè)置標(biāo)題 plt.xlabel("時(shí)間",fontproperties = my_font,fontsize = 18) #設(shè)置x坐標(biāo)標(biāo)注,字體為18號(hào) plt.ylabel("每分鐘對(duì)應(yīng)的溫度",fontproperties = my_font,fontsize = 18) #設(shè)置y坐標(biāo)標(biāo)注 plt.plot(x,y) #繪圖 plt.show() #顯示
二、常見(jiàn)繪圖屬性設(shè)置
1.繪圖符號(hào)(Makers)
符號(hào) | 中文說(shuō)明 | 英文說(shuō)明 |
'.' | 圓點(diǎn) | point marker |
',' | 像素點(diǎn) | pixel marker |
'o' | 圓圈 | circle marker |
'v' | 向下三角形 | triangle_down marker |
'^' | 向上三角形 | triangle_up marker |
'<' | 向左三角形 | triangle_left marker |
'>' | 向右三角形 | triangle_right marker |
'1' | 向下Y形 | tri_down marker |
'2' | 向上Y形 | tri_up marker |
'3' | 向左Y形 | tri_left marker |
'4' | 向右Y形 | tri_right marker |
's' | 方形 | square marker |
'p' | 五邊形 | pentagon marker |
'*' | 星形 | star marker |
'h' | 六角形1 | hexagon1 marker |
'H' | 六角形2 | hexagon2 marker |
'+' | 加號(hào) | plus marker |
'x' | 叉號(hào) | x marker |
'D' | 鉆石形 | diamond marker |
'd' | 鉆石形(?。?/p> | thin_diamond marker |
'|' | 豎線(xiàn) | vline marker |
'_' | 橫線(xiàn) | hline marker |
2.線(xiàn)型(Line Styles)
符號(hào) | 中文說(shuō)明 | 英文說(shuō)明 |
'-' | 實(shí)線(xiàn) | solid line style |
'--' | 虛線(xiàn) | dashed line style |
'-.' | 點(diǎn)劃線(xiàn) | dash-dot line style |
':' | 點(diǎn)線(xiàn) | dotted line style |
3.顏色縮寫(xiě)(Colors)
多種豐富的顏色對(duì)照代碼參見(jiàn):RGB顏色值與十六進(jìn)制顏色碼轉(zhuǎn)換工具 (sioe.cn)
符號(hào) | 中文說(shuō)明 | 英文說(shuō)明 |
'b' | 藍(lán) | blue |
'g' | 綠 | green |
'r' | 紅 | red |
'c' | 青 | cyan |
'm' | 紫 | magenta |
'y' | 黃 | yellow |
'k' | 黑 | black |
'w' | 白 | white |
4.Windows字體中英文名稱(chēng)對(duì)照
中文名稱(chēng) | 英文名稱(chēng) |
黑體 | SimHei |
微軟雅黑 | Microsoft YaHei |
微軟正黑體 | Microsoft JhengHei |
新宋體 | NSimSun |
新細(xì)明體 | PMingLiU |
細(xì)明體 | MingLiU |
標(biāo)楷體 | DFKai-SB |
仿宋 | FangSong |
楷體 | KaiTi |
仿宋_GB2312 | FangSong_GB2312 |
楷體_GB2312 | KaiTi_GB2312 |
面向?qū)ο蠓绞嚼L圖
- matplotlib是一套面向?qū)ο蟮睦L圖庫(kù),圖中的所有部件都是python對(duì)象。
- pyplot是matplotlib仿照MATLAB提供的一套快速繪圖API,它并不是matplotlib本體。
- pyplot雖然用起來(lái)簡(jiǎn)單快捷,但它隱藏了大量的細(xì)節(jié),不能使用一些高級(jí)功能。
- pyplot模塊內(nèi)部保存了當(dāng)前圖表和當(dāng)前子圖等信息,可以分別用gcf()和gca()獲得這兩個(gè)對(duì)象:
- plt.gcf(): "Get current figure"獲取當(dāng)前圖表(Figure對(duì)象)
- plt.gca(): "Get current figure"獲取當(dāng)前子圖(Axes對(duì)象)
- pyplot中的各種繪圖函數(shù),實(shí)際上是在內(nèi)部調(diào)用gca獲取當(dāng)前Axes對(duì)象,然后調(diào)用Axes的方法完成繪圖的。
import matplotlib.pyplot as plt # 獲取當(dāng)前的Figure和Axes對(duì)象 plt.figure(figsize=(4,3)) fig = plt.gcf() axes = plt.gca() print(fig) print(axes)
配置對(duì)象的屬性
matplotlib所繪制的圖表的每一部分都對(duì)應(yīng)一個(gè)對(duì)象,有兩種方式設(shè)置這些對(duì)象的屬性:
通過(guò)對(duì)象的set_*()方法設(shè)置。
通過(guò)pyplot的setp()方法設(shè)置。
同樣也有兩種方法查看對(duì)象的屬性:
通過(guò)對(duì)象的get_*()方法查看。
通過(guò)pyplot的getp()方法查看。
import matplotlib.pyplot as plt import numpy as np # 獲取當(dāng)前的Figure和Axes對(duì)象 plt.figure(figsize=(4,3)) fig = plt.gcf() ; axes = plt.gca() print(fig); print(axes) x = np.arange(0, 5, 0.1) # 調(diào)用plt.plot函數(shù),返回一個(gè)Line2D對(duì)象列表 lines = plt.plot(x, 0.05*x*x); print(lines) # 調(diào)用Line2D對(duì)象的set系列方法設(shè)置屬性值 # 用set_alpha設(shè)置alpha通道,也就是透明度 lines[0].set_alpha(0.5) ; plt.show() # plt.plot函數(shù)可以接受不定個(gè)數(shù)的位置參數(shù),這些位置參數(shù)兩兩配對(duì),生成多條曲線(xiàn)。 lines = plt.plot(x, np.sin(x), x, np.cos(x), x, np.tanh(x)) plt.show() # 使用plt.setp函數(shù)同時(shí)配置多個(gè)對(duì)象的屬性,這里設(shè)置lines列表中所有曲線(xiàn)的顏色和線(xiàn)寬。 plt.setp(lines, color='r', linewidth=4.0);plt.show() # 使用getp方法查看所有的屬性 f = plt.gcf(); plt.getp(f)
import numpy as np import matplotlib.pyplot as plt # 獲取當(dāng)前的Figure和Axes對(duì)象 plt.figure(figsize=(4,3)) fig = plt.gcf() ; axes = plt.gca() print(fig); print(axes) x = np.arange(0, 5, 0.1) # 調(diào)用plt.plot函數(shù),返回一個(gè)Line2D對(duì)象列表 lines = plt.plot(x, 0.05*x*x); print(lines) # 調(diào)用Line2D對(duì)象的set系列方法設(shè)置屬性值 # 用set_alpha設(shè)置alpha通道,也就是透明度 lines[0].set_alpha(0.5) ; plt.show() # plt.plot函數(shù)可以接受不定個(gè)數(shù)的位置參數(shù),這些位置參數(shù)兩兩配對(duì),生成多條曲線(xiàn)。 lines = plt.plot(x, np.sin(x), x, np.cos(x), x, np.tanh(x)) plt.show() # 使用plt.setp函數(shù)同時(shí)配置多個(gè)對(duì)象的屬性,這里設(shè)置lines列表中所有曲線(xiàn)的顏色和線(xiàn)寬。 plt.setp(lines, color='r', linewidth=4.0);plt.show() # 使用getp方法查看所有的屬性 f = plt.gcf(); plt.getp(f) # 查看某個(gè)屬性 print(plt.getp(lines[0],"color")) # 使用對(duì)象的get_*()方法 print(lines[0].get_linewidth()) # Figure對(duì)象的axes屬性是一個(gè)列表,存儲(chǔ)該Figure中的所有Axes對(duì)象。 # 下面代碼查看當(dāng)前Figure的axes屬性,也就是gca獲得的當(dāng)前Axes對(duì)象。 print(plt.getp(f, 'axes')) print(len(plt.getp(f, 'axes'))) print(plt.getp(f, 'axes')[0] is plt.gca()) # 用plt.getp()可以繼續(xù)獲取AxesSubplot對(duì)象的屬性,例如它的lines屬性為子圖中的Line2D對(duì)象列表。 # 通過(guò)這種方法可以查看對(duì)象的屬性值,以及各個(gè)對(duì)象之間的關(guān)系。 all_lines = plt.getp(plt.gca(), "lines");print(all_lines) plt.close() # 關(guān)閉當(dāng)前圖表
繪制多個(gè)子圖
在matplotlib中,一個(gè)Figure對(duì)象可以包括多個(gè)Axes對(duì)象(也就是子圖),一個(gè)Axes代表一個(gè)繪圖區(qū)域。最簡(jiǎn)單的多子圖繪制方式是使用pyplot的subplot函數(shù)。
subplot(numRows, numCols, plotNum)接受三個(gè)參數(shù):
numRows:子圖行數(shù)
numCols:子圖列數(shù)
plotNum:第幾個(gè)子圖(按從左到右,從上到下的順序編號(hào))
import matplotlib.pyplot as plt # 創(chuàng)建3行2列,共計(jì)6個(gè)子圖。 # subplot(323)等價(jià)于subplot(3,2,3)。 # 子圖的編號(hào)是從1開(kāi)始,不是從0開(kāi)始。 fig = plt.figure(figsize=(4,3)) for idx,color in enumerate('rgbcyk'): plt.subplot(321+idx, facecolor=color) plt.show() # 如果新創(chuàng)建的子圖和之前創(chuàng)建的有重疊區(qū)域,則之前的子圖會(huì)被刪除 plt.subplot(221) plt.show() plt.close() # 還可以用多個(gè)高度或?qū)挾炔煌淖訄D相互拼接 fig = plt.figure(figsize=(4,3)) plt.subplot(221) # 第一行左圖 plt.subplot(222) # 第一行右圖 plt.subplot(212) # 第二行整行 plt.show() plt.close()
三、Artist對(duì)象
簡(jiǎn)單類(lèi)型的Artist對(duì)象是標(biāo)準(zhǔn)的繪圖元件,例如Line2D,Rectangle,Text,AxesImage等
容器類(lèi)型的Artist對(duì)象包含多個(gè)Artist對(duì)象使他們組織成一個(gè)整體例如Axis,Axes,F(xiàn)igure對(duì)象
Artist對(duì)象進(jìn)行繪圖的流程
- 創(chuàng)建Figure對(duì)象
- 為Figure對(duì)象創(chuàng)建一個(gè)或多個(gè)Axes對(duì)象
- 調(diào)用Axes對(duì)象的方法來(lái)創(chuàng)建各種簡(jiǎn)單的Artist對(duì)象
import matplotlib.pyplot as plt fig = plt.figure() # 列表用于描述圖片所在的位置以及圖片的大小 ax = fig.add_axes([0.15, 0.1, 0.7, 0.3]) ax.set_xlabel('time') line = ax.plot([1, 2, 3], [1, 2, 1])[0] # ax的lines屬性是一個(gè)包含所有曲線(xiàn)的列表 print(line is ax.lines[0]) # 通過(guò)get_*獲得相應(yīng)的屬性 print(ax.get_xaxis().get_label().get_text()) plt.show()
設(shè)置Artist屬性
get_* 和 set_* 函數(shù)進(jìn)行讀寫(xiě)fig.set_alpha(0.5*fig.get_alpha())
Artist 屬性 | 作用 |
alpha | 透明度,值在0到1之間,0為完全透明,1為完全不透明 |
animated | 布爾值,在繪制動(dòng)畫(huà)效果時(shí)使用 |
axes | 此Artist對(duì)象所在的Axes對(duì)象,可能為None |
clip_box | 對(duì)象的裁剪框 |
clip_on | 是否裁剪 |
clip_path | 裁剪的路徑 |
contains | 判斷指定點(diǎn)是否在對(duì)象上的函數(shù) |
figure | 所在的Figure對(duì)象,可能為None |
label | 文本標(biāo)簽 |
picker | 控制Artist對(duì)象選取 |
transform | 控制偏移旋轉(zhuǎn) |
visible | 是否可見(jiàn) |
zorder | 控制繪圖順序 |
一些例子
import matplotlib.pyplot as plt fig = plt.figure() # 設(shè)置背景色 fig.patch.set_color('g') # 必須更新界面才會(huì)有效果 fig.canvas.draw() plt.show() # artist對(duì)象的所有屬性都可以通過(guò)相應(yīng)的get_*()和set_*()進(jìn)行讀寫(xiě) # 例如設(shè)置下面圖像的透明度 line = plt.plot([1, 2, 3, 2, 1], lw=4)[0] line.set_alpha(0.5) line.set(alpha=0.5, zorder=1) # fig.canvas.draw() # 輸出Artist對(duì)象的所有屬性名以及與之對(duì)應(yīng)的值 print(fig.patch) plt.show()
import matplotlib.pyplot as plt fig = plt.figure() fig.subplots_adjust(top=0.8) ax1 = fig.add_subplot(211) ax1.set_ylabel('volts') ax1.set_title('a sine wave') t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) line, = ax1.plot(t, s, color='blue', lw=2) # Fixing random state for reproducibility np.random.seed(19680801) ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3]) n, bins, patches = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='orange') ax2.set_xlabel('time (s)') plt.show()
Figure容器
最上層的Artist對(duì)象是Figure,包含組成圖表的所有元素
Figure可以包涵多個(gè)Axes(多個(gè)圖表),創(chuàng)建主要有三種方法:
- axes = fig.add_axes([left, bottom, width, height])
- fig, axes = plt.subplots(行數(shù), 列數(shù))
- axes = fig.add_subplot(行數(shù), 列數(shù), 序號(hào))
Figure 屬性 | 說(shuō)明 |
axes | Axes對(duì)象列表 |
patch | 作為背景的Rectangle對(duì)象 |
images | FigureImage對(duì)象列表,用來(lái)顯示圖片 |
legends | Legend對(duì)象列表 |
lines | Line2D對(duì)象列表 |
patches | patch對(duì)象列表 |
texts | Text對(duì)象列表,用來(lái)顯示文字 |
import matplotlib.pyplot as plt # 下面請(qǐng)看一個(gè)多Figure,多Axes,互相靈活切換的例子。 plt.figure(1) # 創(chuàng)建圖表1 plt.figure(2) # 創(chuàng)建圖表2 ax1 = plt.subplot(121) # 在圖表2中創(chuàng)建子圖1 ax2 = plt.subplot(122) # 在圖表2中創(chuàng)建子圖2 x = np.linspace(0, 3, 100) for i in range(5): plt.figure(1) # 切換到圖表1 plt.plot(x, np.exp(i*x/3)) plt.sca(ax1) # 選擇圖表2的子圖1 plt.plot(x, np.sin(i*x)) plt.sca(ax2) # 選擇圖表2的子圖2 plt.plot(x, np.cos(i*x)) ax2.plot(x, np.tanh(i*x)) # 也可以通過(guò)ax2的plot方法直接繪圖 plt.show() plt.close() # 打開(kāi)了兩個(gè)Figure對(duì)象,因此要執(zhí)行plt.close()兩次 plt.close() # 還可以使用subplots函數(shù),一次生成多個(gè)子圖,并返回Figure對(duì)象和Axes對(duì)象數(shù)組。 # 注意subplot和subplots兩個(gè)函數(shù)差一個(gè)s,前者是逐個(gè)生成子圖,后者是批量生成。 fig, axes = plt.subplots(2, 3, figsize=(4,3)) [a,b,c],[d,e,f] = axes print(axes.shape) print(b) plt.show() plt.close()
Axes容器
- 圖像的區(qū)域,有數(shù)據(jù)空間(標(biāo)記為內(nèi)部藍(lán)色框)
- 圖形可以包含多個(gè) Axes,軸對(duì)象只能包含一個(gè)圖形
- Axes 包含兩個(gè)(或三個(gè))Axis對(duì)象,負(fù)責(zé)數(shù)據(jù)限制
- 每個(gè)軸都有一個(gè)標(biāo)題(通過(guò)set_title()設(shè)置)、一個(gè)x標(biāo)簽(通過(guò)set_xLabel()設(shè)置)和一個(gè)通過(guò)set_yLabel()設(shè)置的y標(biāo)簽集。
Axes 屬性 | 說(shuō)明 |
artists | A list of Artist instances |
patch | Rectangle instance for Axes background |
collections | A list of Collection instances |
images | A list of AxesImage |
legends | A list of Legend instances |
lines | A list of Line2D instances |
patches | A list of Patch instances |
texts | A list of Text instances |
xaxis | matplotlib.axis.XAxis instance |
yaxis | matplotlib.axis.YAxis instance |
Axes的方法(Helper method) | 所創(chuàng)建的對(duì)象(Artist ) | 添加進(jìn)的列表(Container) |
ax.annotate - text annotations | Annotate | ax.texts |
ax.bar - bar charts | Rectangle | ax.patches |
ax.errorbar - error bar plots | Line2D and Rectangle | ax.lines and ax.patches |
ax.fill - shared area | Polygon | ax.patches |
ax.hist - histograms | Rectangle | ax.patches |
ax.imshow - image data | AxesImage | ax.images |
ax.legend - axes legends | Legend | ax.legends |
ax.plot - xy plots | Line2D | ax.lines |
ax.scatter - scatter charts | PolygonCollection | ax.collections |
ax.text - text | Text | ax.texts |
subplot2grid函數(shù)進(jìn)行更復(fù)雜的布局。subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs)
- shape為表示表格形狀的元組(行數(shù),列數(shù))
- loc為子圖左上角所在的坐標(biāo)元組(行,列)
- rowspan和colspan分別為子圖所占據(jù)的行數(shù)和列數(shù)
import matplotlib.pyplot as plt fig = plt.figure(figsize=(6,6)) ax1 = plt.subplot2grid((3,3),(0,0),colspan=2) ax2 = plt.subplot2grid((3,3),(0,2),rowspan=2) ax3 = plt.subplot2grid((3,3),(1,0),rowspan=2) ax4 = plt.subplot2grid((3,3),(2,1),colspan=2) ax5 = plt.subplot2grid((3,3),(1,1)) plt.show() plt.close()
坐標(biāo)軸上的刻度線(xiàn)、刻度文本、坐標(biāo)網(wǎng)格及坐標(biāo)軸標(biāo)題等
set_major_* set_minor_*
get_major_* get_minor_*
import numpy as np import matplotlib.pyplot as plt # plt.figure creates a matplotlib.figure.Figure instance fig = plt.figure() rect = fig.patch # a rectangle instance rect.set_facecolor('yellow') ax1 = fig.add_axes([0.1, 0.3, 1,1]) rect = ax1.patch rect.set_facecolor('orange') for label in ax1.xaxis.get_ticklabels(): # label is a Text instance label.set_color('red') label.set_rotation(45) label.set_fontsize(16) for line in ax1.yaxis.get_ticklines(): # line is a Line2D instance line.set_color('green') line.set_markersize(5) line.set_markeredgewidth(3) plt.show()
坐標(biāo)軸刻度設(shè)置
matplotlib會(huì)按照用戶(hù)所繪制的圖的數(shù)據(jù)范圍自動(dòng)計(jì)算,但有的時(shí)候也需要我們自定義。
我們有時(shí)候希望將坐標(biāo)軸的文字改為我們希望的樣子,比如特殊符號(hào),年月日等。
# 修改坐標(biāo)軸刻度的例子 # 配置X軸的刻度線(xiàn)的位置和文本,并開(kāi)啟副刻度線(xiàn) # 導(dǎo)入fractions包,處理分?jǐn)?shù) import numpy as np import matplotlib.pyplot as plt from fractions import Fraction # 導(dǎo)入ticker,刻度定義和文本格式化都在ticker中定義 from matplotlib.ticker import MultipleLocator, FuncFormatter x = np.arange(0, 4*np.pi, 0.01) fig, ax = plt.subplots(figsize=(8,4)) plt.plot(x, np.sin(x), x, np.cos(x)) # 定義pi_formatter, 用于計(jì)算刻度文本 # 將數(shù)值x轉(zhuǎn)換為字符串,字符串中使用Latex表示數(shù)學(xué)公式。 def pi_formatter(x, pos): frac = Fraction(int(np.round(x / (np.pi/4))), 4) d, n = frac.denominator, frac.numerator if frac == 0: return "0" elif frac == 1: return "$\pi$" elif d == 1: return r"${%d} \pi$" % n elif n == 1: return r"$\frac{\pi}{%d}$" % d return r"$\frac{%d \pi}{%d}$" % (n, d) # 設(shè)置兩個(gè)坐標(biāo)軸的范圍 plt.ylim(-1.5,1.5) plt.xlim(0, np.max(x)) # 設(shè)置圖的底邊距 plt.subplots_adjust(bottom = 0.15) plt.grid() #開(kāi)啟網(wǎng)格 # 主刻度為pi/4 # 用MultipleLocator以指定數(shù)值的整數(shù)倍放置刻度線(xiàn) ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) ) # 主刻度文本用pi_formatter函數(shù)計(jì)算 # 使用指定的函數(shù)計(jì)算刻度文本,這里使用我們剛剛編寫(xiě)的pi_formatter函數(shù) ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) ) # 副刻度為pi/20 ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) ) # 設(shè)置刻度文本的大小 for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(16) plt.show() plt.close()
import datetime import numpy as np import matplotlib.pyplot as plt # 準(zhǔn)備數(shù)據(jù) x = np.arange(0,10,0.01) y = np.sin(x) # 將數(shù)據(jù)轉(zhuǎn)換為datetime對(duì)象列表 date_list = [] date_start = datetime.datetime(2000,1,1,0,0,0) delta = datetime.timedelta(days=1) for i in range(len(x)): date_list.append(date_start + i*delta) # 繪圖,將date_list作為x軸數(shù)據(jù),當(dāng)作參數(shù)傳遞 fig, ax = plt.subplots(figsize=(10,4)) plt.plot(date_list, y) # 設(shè)定標(biāo)題 plt.title('datetime example') plt.ylabel('data') plt.xlabel('Date') plt.show() plt.close()
如果數(shù)據(jù)中本來(lái)就有時(shí)間日期信息,可以使用strptime和strftime直接轉(zhuǎn)換。
使用strptime函數(shù)將字符串轉(zhuǎn)換為time,使用strftime將time轉(zhuǎn)換為字符串。
python中的時(shí)間日期格式化符號(hào):
符號(hào) | 意義 |
%y | 兩位數(shù)的年份表示(00-99) |
%Y | 四位數(shù)的年份表示(000-9999) |
%m | 月份(01-12) |
%d | 月內(nèi)中的一天(0-31) |
%H | 24小時(shí)制小時(shí)數(shù)(0-23) |
%I | 12小時(shí)制小時(shí)數(shù)(01-12) |
%M | 分鐘數(shù)(00=59) |
%S | 秒(00-59) |
%a | 本地簡(jiǎn)化星期名稱(chēng) |
%A | 本地完整星期名稱(chēng) |
%b | 本地簡(jiǎn)化的月份名稱(chēng) |
%B | 本地完整的月份名稱(chēng) |
%c | 本地相應(yīng)的日期表示和時(shí)間表示 |
%j | 年內(nèi)的一天(001-366) |
%p | 本地A.M.或P.M.的等價(jià)符 |
%U | 一年中的星期數(shù)(00-53)星期天為星期的開(kāi)始 |
%w | 星期(0-6),星期天為星期的開(kāi)始 |
%W | 一年中的星期數(shù)(00-53)星期一為星期的開(kāi)始 |
%x | 本地相應(yīng)的日期表示 |
%X | 本地相應(yīng)的時(shí)間表示 |
%Z | 當(dāng)前時(shí)區(qū)的名稱(chēng) |
%% | %號(hào)本身 |
總結(jié)
到此這篇關(guān)于python使用Matplotlib繪圖及設(shè)置的文章就介紹到這了,更多相關(guān)python Matplotlib繪圖設(shè)置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python標(biāo)準(zhǔn)庫(kù)sys和OS的函數(shù)使用方法與實(shí)例詳解
這篇文章主要介紹了python標(biāo)準(zhǔn)庫(kù)sys和OS的函數(shù)使用方法與實(shí)例詳解,需要的朋友可以參考下2020-02-02一文詳解Python灰色預(yù)測(cè)模型實(shí)現(xiàn)示例
這篇文章主要為大家介紹了Python灰色預(yù)測(cè)模型實(shí)現(xiàn)示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02Python延時(shí)操作實(shí)現(xiàn)方法示例
這篇文章主要介紹了Python延時(shí)操作實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python基于sched庫(kù)與time庫(kù)實(shí)現(xiàn)延時(shí)操作的方法,需要的朋友可以參考下2018-08-08Python numpy.array()生成相同元素?cái)?shù)組的示例
今天小編就為大家分享一篇Python numpy.array()生成相同元素?cái)?shù)組的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11更新升級(jí)python和pip版本后不生效的問(wèn)題解決
這篇文章主要介紹了更新升級(jí)python和pip版本后不生效的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Python 語(yǔ)言實(shí)現(xiàn)六大查找算法
本文給大家分享Python 語(yǔ)言實(shí)現(xiàn)六大查找算法,針對(duì)每種算法通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-06-06