Matplot pyplot绘制单图,多子图不同样式详解,这一篇就够了
Matplot pyplot繪制單圖,多子圖不同樣式詳解,這一篇就夠了
- 1. 單圖單線
- 2. 單圖多線不同樣式(紅色圓圈、藍色實線、綠色三角等)
- 3. 使用關鍵字字符串繪圖(data 可指定依賴值為:numpy.recarray 或 pandas.DataFrame)
- 4. 使用分類變量繪圖(繪制條形圖、散點圖、折線圖)
- 5. 多子表多軸及共享軸
- 6. 多子表
- 6.1 多子表垂直堆疊
- 6.2 多子表水平堆疊
- 6.3 多子表垂直水平堆疊
- 6.4 多子表共享軸(去除垂直、水平堆疊子表之間寬度和高度之間的縫隙)
- 6.5 多子表極坐標風格軸
- 6.6 多子表源碼
- 7. 圖表中文本標注(箭頭注釋)
- 8. 對數軸和其他非線性軸
- 參考
matplotlib.pyplot 是使 matplotlib 像 MATLAB 一樣工作的函數集合。這篇博客將介紹
- 單圖單線
- 單圖多線不同樣式(紅色圓圈、藍色實線、綠色三角等)
- 使用關鍵字字符串繪圖(data 可指定依賴值為:numpy.recarray 或 pandas.DataFrame)
- 使用分類變量繪圖(繪制條形圖、散點圖、折線圖)
- 多子表多軸及共享軸
- 多子表(水平堆疊、垂直堆疊、水平垂直堆疊、水平垂直堆疊共享軸、水平垂直堆疊去掉子圖中間的冗余xy標簽及間隙、極坐標風格軸示例);
-
plt.set_title(‘simple plot’, loc = ‘left’)
設置表示標題,默認位于中間,也可位于left靠左,right靠右 -
t = plt.xlabel(‘Smarts’, fontsize=14, color=‘red’)
表示設置x標簽的文本,字體大小,顏色 -
plt.plot([1, 2, 3, 4])
如果提供的單個列表或數組,matplot假定提供的是y的值;x默認跟y個數一致,但從0開始,表示x:[0,1,2,3] -
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
表示x:[1,2,3,4],y:[1,4,9,16] -
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], ‘ro’)
表示x:[1,2,3,4],y:[1,4,9,16],然后指定線的顏色和樣式(ro:紅色圓圈,b-:藍色實線等) -
plt.axis([0, 6, 0, 20])
plt.axix[xmin, xmax, ymin, ymax] 表示x軸的刻度范圍[0,6], y軸的刻度范圍[0,20] -
plt.bar(names, values) # 條形圖
-
plt.scatter(names, values) # 散點圖
-
plt.plot(names, values) # 折線圖
-
fig, ax = plt.subplots(2, sharex=True, sharey=True) 可創建多表,并指定共享x,y軸,然后ax[0],ax[1]繪制data
-
fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True) 可創建多表,并指定共享x,y軸
-
fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True) 可創建多表,垂直堆疊表 2行1列
-
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) 可創建多表,水平堆疊表 1行2列
-
fig, (ax1, ax2) = plt.subplots(2, 2, sharex=True, sharey=True,hspace=0,wspace=0) 可創建多表,水平垂直堆疊表 2行2列,共享x,y軸,并去除子圖寬度和高度之間的縫隙
共享x,y軸表示共享x,y軸的刻度及值域;
- plt.text(60, .025, r’μ=100,σ=15\mu=100,\ \sigma=15μ=100,?σ=15’)
表示在60,0.025處進行文本(μ=100,σ=15\mu=100,\ \sigma=15μ=100,?σ=15)的標注
1. 單圖單線
# 單圖單線
import matplotlib.pyplot as plt# 如果提供單個列表或數組,matplotlib 會假定它是一個 y 值序列,并自動為您生成 x 值。
# 由于 python 范圍從 0 開始,默認的 x 向量與 y 具有相同的長度,但從 0 開始。因此 x 數據是 [0, 1, 2, 3]
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()# 對于每對 x, y 參數,都有一個可選的第三個參數,它是指示繪圖顏色和線型的格式字符串。
# 格式字符串的字母和符號來自 MATLAB,將顏色字符串與線型字符串連接起來。默認格式字符串是“b-”,這是一條藍色實線。'ro'紅色圓圈
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20]) # 刻度軸的范圍,x:0~6,y:0~20
plt.show()
2. 單圖多線不同樣式(紅色圓圈、藍色實線、綠色三角等)
- ’b-‘:藍色實線
- ‘ro’:紅色圓圈
- ‘r–’:紅色破折號
- ‘bs’:藍色方形
- ‘g^’:綠色三角
線的顏色和樣式可參考
mark標記:
‘.’ point marker
‘,’ pixel marker
‘o’ circle marker
‘v’ triangle_down marker
‘^’ triangle_up marker
‘<’ triangle_left marker
‘>’ triangle_right marker
‘1’ tri_down marker
‘2’ tri_up marker
‘3’ tri_left marker
‘4’ tri_right marker
‘8’ octagon marker
‘s’ square marker
‘p’ pentagon marker
‘P’ plus (filled) marker
‘*’ star marker
‘h’ hexagon1 marker
‘H’ hexagon2 marker
‘+’ plus marker
‘x’ x marker
‘X’ x (filled) marker
‘D’ diamond marker
‘d’ thin_diamond marker
‘|’ vline marker
‘_’ hline marker
- 支持的顏色:
‘b’ blue 藍色
‘g’ green 綠色
‘r’ red 紅色
‘c’ cyan 蘭青色
‘m’ magenta 紫色
‘y’ yellow 黃色
‘k’ black 黑色
‘w’ white 白色
- 支持的點的樣式:
‘-’ solid line style 實線
‘–’ dashed line style 虛線
‘-.’ dash-dot line style 點劃線
‘:’ dotted line style 虛線
import matplotlib.pyplot as pltimport numpy as np# 以 200 毫秒的間隔均勻采樣時間
t = np.arange(0., 5., 0.2)# 'r--':紅色破折號, 'bs':藍色方形 ,'g^':綠色三角
plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^')
plt.show()
3. 使用關鍵字字符串繪圖(data 可指定依賴值為:numpy.recarray 或 pandas.DataFrame)
import matplotlib.pyplot as pltimport numpy as np# 使用關鍵字字符串繪圖(data 可指定依賴值為:numpy.recarray 或 pandas.DataFrame)
data = {'a': np.arange(50), # 1個參數,表示[0,1,2...,50]'c': np.random.randint(0, 50, 50), # 表示產生50個隨機數[0,50)'d': np.random.randn(50)} # 返回呈標準正態分布的值(可能正,可能負)
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100print(np.arange(50))
print(np.random.randint(0, 50, 50))
print(np.random.randn(50))
print(data['b'])
print(data['d'])plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
4. 使用分類變量繪圖(繪制條形圖、散點圖、折線圖)
- plt.bar(names, values) # 條形圖
- plt.scatter(names, values) # 散點圖
- plt.plot(names, values) # 折線圖
import matplotlib.pyplot as pltimport numpy as np# 用分類變量繪圖
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]plt.figure(figsize=(9, 3))plt.subplot(131)
plt.bar(names, values) # 條形圖
plt.subplot(132)
plt.scatter(names, values) # 散點圖
plt.subplot(133)
plt.plot(names, values) # 折線圖
plt.suptitle('Categorical Plotting')
plt.show()# 控制線條屬性:線條有許多可以設置的屬性:線寬、虛線樣式、抗鋸齒等;
lines = plt.plot(10, 20, 30, 100)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
line, = plt.plot(np.arange(50), np.arange(50) + 10, '-')
plt.show()
5. 多子表多軸及共享軸
多子表多軸,先用點再用線連接,效果圖如下:
多子表多軸,繪制點效果圖如下:
import matplotlib.pyplot as plt
import numpy as np# 多表和多軸
def f(t):return np.exp(-t) * np.cos(2 * np.pi * t)t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)plt.figure()
plt.subplot(211) # 2行1列共倆個子表,中間的2,1,1同211
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') # 繪制藍色圓圈(t1,f(t1)),然后用黑色線連接值plt.subplot(212)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')
plt.show()# 圖1去掉t2,f(t2)并沒有把結果進行連線
plt.figure()
plt.subplot(211) # 2行1列共倆個子表,中間的2,1,1同211
plt.plot(t1, f(t1), 'bo')plt.subplot(212)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')
plt.show()
多子表共享y軸,效果圖如下:
fig, (ax1, ax2) = plt.subplots(2, sharey=True) 共享y軸
# 多子表共享軸
import numpy as np
import matplotlib.pyplot as plt# 構建繪圖數據
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)# 繪制倆個子圖,共享y軸
fig, (ax1, ax2) = plt.subplots(2, sharey=True)ax1.plot(x1, y1, 'ko-')
ax1.set(title='A tale of 2 subplots', ylabel='Damped oscillation')ax2.plot(x2, y2, 'r.-')
ax2.set(xlabel='time (s)', ylabel='Undamped')plt.show()
6. 多子表
6.1 多子表垂直堆疊
6.2 多子表水平堆疊
6.3 多子表垂直水平堆疊
隱藏頂部2子圖的x標簽,和右側2子圖的y標簽,效果圖如下:
同上圖,共享x列,y行的坐標軸~
6.4 多子表共享軸(去除垂直、水平堆疊子表之間寬度和高度之間的縫隙)
共享x軸并對齊,效果圖如下:
共享x,y軸效果如下圖:
共享x,y軸表示共享其值域及刻度;
對于共享軸的子圖,一組刻度標簽就足夠了。內部軸的刻度標簽由 sharex 和 sharey 自動刪除。子圖之間仍然有一個未使用的空白空間;
要精確控制子圖的定位,可以使用fig.add_gridspec(hspace=0) 減少垂直子圖之間的高度。fig.add_gridspec(wspace=0) 減少水平子圖之間的高度。
共享x,y軸,并刪除多個子表之間高度的縫隙,效果如下圖:
共享x,y軸,并刪除多個子表冗余xy標簽,及子圖之間寬度、高度的縫隙,效果如下圖:
6.5 多子表極坐標風格軸
6.6 多子表源碼
# 多子表示例:水平堆疊、垂直堆疊、水平垂直堆疊、水平垂直堆疊共享軸、水平垂直堆疊去掉子圖中間的冗余xy標簽及間隙;import matplotlib.pyplot as plt
import numpy as np# 樣例數據
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)def single_plot():fig, ax = plt.subplots()ax.plot(x, y)ax.set_title('A single plot')plt.show()def stacking_plots_one_direction():# pyplot.subplots 的前兩個可選參數定義子圖網格的行數和列數。# 當僅在一個方向上堆疊時,返回的軸是一個一維 numpy 數組,其中包含創建的軸列表。fig, axs = plt.subplots(2)fig.suptitle('Vertically stacked subplots')axs[0].plot(x, y)axs[1].plot(x, -y)plt.show()# 當只創建幾個 Axes,可將它們立即解壓縮到每個 Axes 的專用變量會很方便fig, (ax1, ax2) = plt.subplots(2)fig.suptitle('Vertically stacked subplots')ax1.plot(x, y)ax2.plot(x, -y)plt.show()# 水平方向堆疊子圖fig, (ax1, ax2) = plt.subplots(1, 2)fig.suptitle('Horizontally stacked subplots')ax1.plot(x, y)ax2.plot(x, -y)plt.show()def stacking_plots_two_directions():# 在兩個方向上堆疊子圖時,返回的 axs 是一個 2D NumPy 數組。表示倆行倆列的表fig, axs = plt.subplots(2, 2)axs[0, 0].plot(x, y)axs[0, 0].set_title('Axis [0, 0]')axs[0, 1].plot(x, y, 'tab:orange')axs[0, 1].set_title('Axis [0, 1]')axs[1, 0].plot(x, -y, 'tab:green')axs[1, 0].set_title('Axis [1, 0]')axs[1, 1].plot(x, -y, 'tab:red')axs[1, 1].set_title('Axis [1, 1]')for ax in axs.flat:ax.set(xlabel='x-label', ylabel='y-label')# 隱藏頂部2子圖的x標簽,和右側2子圖的y標簽for ax in axs.flat:ax.label_outer()plt.show()# 也可以在 2D 中使用元組解包將所有子圖分配給專用變量fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)fig.suptitle('Sharing x per column, y per row')ax1.plot(x, y)ax2.plot(x, y ** 2, 'tab:orange')ax3.plot(x, -y, 'tab:green')ax4.plot(x, -y ** 2, 'tab:red')for ax in fig.get_axes():ax.label_outer()plt.show()def sharing_axs():fig, (ax1, ax2) = plt.subplots(2)fig.suptitle('Axes values are scaled individually by default')ax1.plot(x, y)ax2.plot(x + 1, -y)plt.show()# 共享x軸,對齊x軸fig, (ax1, ax2) = plt.subplots(2, sharex=True)fig.suptitle('Aligning x-axis using sharex')ax1.plot(x, y)ax2.plot(x + 1, -y)plt.show()# 共享x,y軸fig, axs = plt.subplots(3, sharex=True, sharey=True)fig.suptitle('Sharing both axes')axs[0].plot(x, y ** 2)axs[1].plot(x, 0.3 * y, 'o')axs[2].plot(x, y, '+')plt.show()# 對于共享軸的子圖,一組刻度標簽就足夠了。內部軸的刻度標簽由 sharex 和 sharey 自動刪除。子圖之間仍然有一個未使用的空白空間;# 要精確控制子圖的定位,可以使用 Figure.add_gridspec 顯式創建一個 GridSpec,然后調用其子圖方法。例如可以使用 add_gridspec(hspace=0) 減少垂直子圖之間的高度。fig = plt.figure()gs = fig.add_gridspec(3, hspace=0)axs = gs.subplots(sharex=True, sharey=True)fig.suptitle('Sharing both axes')axs[0].plot(x, y ** 2)axs[1].plot(x, 0.3 * y, 'o')axs[2].plot(x, y, '+')# 隱藏除了底部x標簽及刻度外,其他子圖的x標簽及刻度# label_outer 是一種從不在網格邊緣的子圖中刪除標簽和刻度的方便方法。for ax in axs:ax.label_outer()plt.show()# 2*2多圖堆疊,共享x,y軸,并去除子圖之間寬度和高度之間的縫隙fig = plt.figure()gs = fig.add_gridspec(2, 2, hspace=0, wspace=0)(ax1, ax2), (ax3, ax4) = gs.subplots(sharex='col', sharey='row')fig.suptitle('Sharing x per column, y per row')ax1.plot(x, y)ax2.plot(x, y ** 2, 'tab:orange')ax3.plot(x + 1, -y, 'tab:green')ax4.plot(x + 2, -y ** 2, 'tab:red')for ax in axs.flat:ax.label_outer()plt.show()# 復雜結構的共享軸代碼fig, axs = plt.subplots(2, 2)axs[0, 0].plot(x, y)axs[0, 0].set_title("main")axs[1, 0].plot(x, y ** 2)axs[1, 0].set_title("shares x with main")axs[1, 0].sharex(axs[0, 0])axs[0, 1].plot(x + 1, y + 1)axs[0, 1].set_title("unrelated")axs[1, 1].plot(x + 2, y + 2)axs[1, 1].set_title("also unrelated")fig.tight_layout()plt.show()def polar_axs():fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))ax1.plot(x, y)ax2.plot(x, y ** 2)plt.title('polar axs')plt.show()# 僅單表
single_plot()# 僅單方向堆疊子表(垂直方向堆疊,水平方向堆疊)
stacking_plots_one_direction()# 水平垂直堆疊子圖
stacking_plots_two_directions()# 共享軸
sharing_axs()# 極坐標風格軸
polar_axs()
7. 圖表中文本標注(箭頭注釋)
簡單文本標注(只設置要標注的文本內容,起始位置),效果圖如下:
# 表示在60,0.025處進行文本('$\mu=100,\ \sigma=15$')的標注,
# 字符串前面的 r 很重要——它表示字符串是一個原始字符串,而不是將反斜杠視為 python 轉義
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
文本標注箭頭效果圖如下:(需設置箭頭起始位置,文本起始位置,文本值)
# 文本的一個常見用途是對繪圖的某些特征進行注釋,而 annotate 方法提供了輔助功能來簡化注釋。
# 在注釋中,有兩點需要考慮:由參數 xy 表示的被注釋的位置和文本 xytext 的位置。這兩個參數都是 (x, y) 元組。
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='yellow', shrink=0.05),)
# 文本標注
import matplotlib.pyplot as plt
import numpy as np# 簡單文本注釋
def simplt_text():mu, sigma = 100, 15x = mu + sigma * np.random.randn(10000)# 直方圖數據n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)# 設置x標簽的文本,字體大小,顏色t = plt.xlabel('Smarts', fontsize=14, color='red')plt.ylabel('Probability')plt.title('Histogram of IQ', loc='left')# 表示在60,0.025處進行文本('$\mu=100,\ \sigma=15$')的標注, 字符串前面的 r 很重要——它表示字符串是一個原始字符串,而不是將反斜杠視為 python 轉義plt.text(60, .025, r'$\mu=100,\ \sigma=15$')plt.axis([40, 160, 0, 0.03])plt.grid(True)plt.show()# 箭頭文本標注
def annotation_text():ax = plt.subplot()t = np.arange(0.0, 5.0, 0.01)s = np.cos(2 * np.pi * t)line, = plt.plot(t, s, lw=2)# 文本的一個常見用途是對繪圖的某些特征進行注釋,而 annotate 方法提供了輔助功能來簡化注釋。# 在注釋中,有兩點需要考慮:由xy: 箭頭位置,xytext:文本位置。這兩個參數都是 (x, y) 元組。plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='yellow', shrink=0.05),)plt.ylim(-2, 2)plt.show()# 簡單文本注釋
simplt_text()# 箭頭文本標注
annotation_text()
8. 對數軸和其他非線性軸
線性軸 VS 對數軸 VS 線性對稱軸 VS logit軸:
# matplotlib.pyplot 不僅支持線性軸刻度,還支持對數和 logit 刻度import matplotlib.pyplot as plt
import numpy as np# 線性軸 對數軸 對稱對數軸 logit軸
def logit_plot():# 設置種子,以保證隨機可重復性顯現np.random.seed(19680801)# 在開區間(0,1)補充一些數據# 從正態(高斯)分布中抽取隨機樣本y = np.random.normal(loc=0.5, scale=0.4, size=1000)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y))# 繪制不同坐標軸維度的數據plt.figure()# 線性plt.subplot(221)plt.plot(x, y)plt.yscale('linear')plt.title('linear')plt.grid(True)# 對數plt.subplot(222)plt.plot(x, y)plt.yscale('log')plt.title('log')plt.grid(True)# symmetric log對稱對象軸plt.subplot(223)plt.plot(x, y - y.mean())plt.yscale('symlog', linthresh=0.01)plt.title('symlog')plt.grid(True)# logitplt.subplot(224)plt.plot(x, y)plt.yscale('logit')plt.title('logit')plt.grid(True)# 調整子圖的布局,因為logit會占用比其他更多的空間,y在"1 - 10^{-3}"plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,wspace=0.35)plt.show()# matplotlib.pyplot 不僅支持線性軸刻度,還支持對數和 logit 刻度
# 線性軸 對數軸 對稱對數軸 logit軸
logit_plot()
參考
- https://matplotlib.org/stable/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
- https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplot_demo.html
- https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html
總結
以上是生活随笔為你收集整理的Matplot pyplot绘制单图,多子图不同样式详解,这一篇就够了的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 妄想山海肋部化石哪里比较多?
- 下一篇: 放假个性签名幽默