天天看點

python 可視化:fig, ax = plt.subplots()畫多表圖的3中常見樣例 & 自定義圖表格式一、fig, ax = plt.subplots()的作用?

目錄

一、fig, ax = plt.subplots()的作用?

二、參數的含義?

三、怎麼在一個圖上排列多個子圖?

四、怎麼把多個子圖一起合并到一個圖上?

《Python for Data Analysis》 2nd Edition

一、fig, ax = plt.subplots()的作用?

它是用來建立 總畫布/figure“視窗”的,有figure就可以在上邊(或其中一個子網格/subplot上)作圖了,(fig:是figure的縮寫)。

  • plt.subplot(111)是plt.subplot(1, 1, 1)另一個寫法而已[引用連結],更完整的寫法是plt.subplot(nrows=1, ncols=1, index=1)[官網matplot.pyplot.subplot連結];
  • fig, ax = plt.subplots()等價于fig, ax = plt.subplots(11)[引用連結]。
  • fig, axes = plt.subplots(23):即表示一次性在figure上建立成2*3的網格,使用plt.subplot()隻能一個一個的添加[引用連結]:
fig = plt.figure()
ax = plt.subplot(231)
ax = plt.subplot(232)
ax = plt.subplot(233)
ax = plt.subplot(234)
ax = plt.subplot(235)
ax = plt.subplot(236)
           

二、參數的含義?

首先看 fig = plt.figure()
matpltlib.pyplot.figure(
num = None,               # 設定figure名稱。系統預設按數字升序命名的figure_num(透視表輸出視窗)e.g. “figure1”。可自行設定figure名稱,名稱或是INT,或是str類型;
figsize=None,             # 設定figure尺寸。系統預設指令是rcParams["figure.fig.size"] = [6.4, 4.8],即figure長寬為6.4 * 4.8;
dpi=None,                 # 設定figure像素密度。系統默指令是rcParams["sigure.dpi"] = 100;
facecolor=None,           # 設定figure背景色。系統預設指令是rcParams["figure.facecolor"] = 'w',即白色white;
edgecolor=None, frameon=True,    # 設定要不要繪制輪廓&輪廓顔色。系統預設繪制輪廓,輪廓染色rcParams["figure.edgecolor"]='w',即白色white;
FigureClass=<class 'matplotlib.figure.Figure'>,   # 設定使不使用一個figure模闆。系統預設不使用;
clear=False,                     # 設定當同名figure存在時,是否替換它。系統預設False,即不替換。
**kwargs)
           
然後看ax = plt.subplot()

三、怎麼在一個圖上排列多個子圖?

比如說我們想畫個2*2的子圖,每個子圖對應一個表。

  • 先重點考慮2個步驟。

· 第1個步驟:建立多元視窗:

fig, axes = plt.subplots(2, 2)  # 此處是一個2*2的圖
           

· 第2個步驟:設定各個透視子圖在視窗的位置:

data.plot.bar(ax=axes[1,1], color='b', alpha=0.5)  # ax=[1,1] 即位置是第2行、第二列。(python從0開始計數,是以“1”代表第2的)

data.plot.barh(ax=axes[0,1], color='k', alpha=0.5) # alpha:設定圖表的透明度;
           
  • 再添加子透視圖代碼。

· 第3個步驟:得到完整的代碼:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2)

data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))

data.plot.bar(ax=axes[1,1], color='b', alpha = 0.5)
data.plot.barh(ax=axes[0,1], color='k', alpha=0.5)

plt.show()
           
python 可視化:fig, ax = plt.subplots()畫多表圖的3中常見樣例 &amp; 自定義圖表格式一、fig, ax = plt.subplots()的作用?

四、怎麼把多個子圖一起合并到一個圖上?

最主要的一點是讓多個圖線共用一個x坐标軸。

  • 語句規定N個折線圖共用一個x坐标(注意:y軸分主副軸):
import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots(1, 1)             # 做1*1個子圖,等價于 " fig, ax1 = plt.subplot() ",等價于 " fig, ax1 = plt.subplots() "

ax2 = ax1.twinx()                         # 讓2個子圖的x軸一樣,同時建立副坐标軸。

# 作y=sin(x)函數
x1 = np.linspace(0, 4 * np.pi, 100)
y1 = np.sin(x1)
ax1.plot(x1, y1)

#  作y = cos(x)函數
x2 = np.linspace(0, 4 * np.pi, 100)       # 表示在區間[0, 4π]之間取100個點(作為橫坐标,“線段是有無數多個點組成的”)。
y2 = np.cos(x2)
ax2.plot(x2, y2)

plt.savefig('sin_cos_2.png')               # 将視窗另存為png格式圖檔
           
python 可視化:fig, ax = plt.subplots()畫多表圖的3中常見樣例 &amp; 自定義圖表格式一、fig, ax = plt.subplots()的作用?

如果需要主副y軸都一樣:就把ax1和ax2它倆用ax一個取代了。

  • 自定義圖表樣式:比如旋轉x軸标簽、上邊和右邊的坐标軸不顯示、曲線和y軸對齊等
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['SimHei']              # 解決不能輸出中文的問題。不區分大小寫,即SimHei’效果等價于‘simhei’,中括号可以不要
plt.rcParams['figure.autolayout'] = True              # 解決不能完整顯示的問題(比如因為餅圖太大,顯示視窗太小)
  
fig, ax = plt.subplots(1, 1, figsize=(12, 9))         # 進一步設定fig的size為12*9

ax.spines['top'].set_visible(False)                   # 不顯示圖表框的上邊框
ax.spines['right'].set_visible(False)                 # 不顯示圖表框的右邊框

ax.set_xlim(0, 10)                                    # 有時候x軸不會從0顯示,使得折線圖和y軸有間隙
ax.set_ylim(0, 1.3e8)                                 # 和x軸同理

plt.xticks(range(0, 10), fontsize=12, rotation=80)    # 針對x軸的标簽,指定我們想要設定的範圍是(0, 10), 字型大小是12, 逆時針旋轉80°

plt.tick_params(bottom='off', left='off', labelbottom='on', lableleft='on')  # 使x軸和y軸不帶比例辨別點, labelbottom設定下邊、即x軸的标簽是否顯示。

< blabla... >

plt.suptitle('自定義圖表', fontsize=400, ha='center')  # 即标題在x軸和y軸形成的方框内部,如下圖(詳細用法見下注釋)。如果需要标題在這上方,使用 plt.title(blabla)            
plt.show()
           
"""
對于multiple subplots一般情況下,

1)設定 plt.xticks(range(0, 10))隻會對最後一個ax起作用。要想作用于所有subplots,要這樣:
for ax in axes:
    ax.set_xticks(range(0, 10))

2)标題:顯示中文方面-在各個子圖上要這樣:
plt.title('某個子圖的中文title', fontproperties='simhei'),
因為plt.rcParams['font.family'] = 'simhei' 隻對整體的标題是有效的。
整體的标題要這樣設定:
plt.suptitle(‘全體子圖的中文title’)

3)xticks的旋轉方面。例如上面的主副坐标軸的共x軸,要這樣:
ax1.set_xticklabels(['str format labels'], rotation=80)
而這樣的設定無效:plt.xticks(x, rotation=80)。
"""
           
python 可視化:fig, ax = plt.subplots()畫多表圖的3中常見樣例 &amp; 自定義圖表格式一、fig, ax = plt.subplots()的作用?

注:

matplotlib.pyplot.suptitle(
t,                          # text縮寫。即标題文字。
fontsize | size,            # 設定字型大小。
x,                          # 設定标題相對于x軸的位置,預設是'0.5'。
y,                          # 設定标題相對于y軸的位置,預設是'0.98'。
ha | horizontalalignment,   # 和參數x一起使用,設定标題水準方位,預設是‘center’。共3個可選值{'center', 'left', right'}。
va | verticalalignment,     # 和參數y一起使用,設定标題垂直方位, 預設是'top'。共4個可選值{'top', 'center', 'bottom', 'baseline'}。
fontweight | weight         # 設定字型權重。
)