Matplotlib是Python中用的最多的2D圖形繪圖庫,學好Matplotlib的用法可以幫助我們在統計分析中更靈活的展示各種數據的狀態,它可與 NumPy 一起使用。
1、創建方式
import matplotlib.pyplot as plt
import numpy as np # 配合使用
import pandas as pd # 配合使用
2、圖片大小、標題、
plt.figure(figsize=(9, 3)) # 圖片大小:長和寬
plt.title("Abnormal point")
3、分圖
plt.figure(1, figsize=(9, 3)) # 圖1
plt.figure(2, figsize=(9, 3)) # 圖2
plt.figure(3, figsize=(9, 3)) # 圖3
plt.figure(4, figsize=(9, 3)) # 圖4
4、子圖
# 矩陣式排列-兩行兩列
plt.subplot(2, 2, 1) # 子圖1
plt.subplot(2, 2, 2) # 子圖2
plt.subplot(2, 2, 3) # 子圖3
plt.subplot(2, 2, 4) # 子圖4
5、subplot加主標題和副標題?
# 有suptitle這個函數,專門生成總標題的
plt.suptitle('Main titile', fontsize=14)
plt.subplot(2, 2, 1)
plt.title('subtitle1') # 子圖1的標題
plt.subplot(2, 2, 2)
plt.title('subtitle2') # 子圖2的標題
plt.subplot(2, 2, 3)
plt.title('subtitle3') # 子圖3的標題
plt.subplot(2, 2, 4)
plt.title('subtitle4') # 子圖4的標題
6、另一種subplot方法
fig, ax_arr = plt.subplots(4, sharex=True)
fig.set_size_inches(12, 8)
pd.Series(data=y, index=x).plot(ax=ax_arr[0], color="b", linestyle='-')
ax_arr[0].set_title("Original sequence")
pd.Series(data=decompose_model.trend, index=x).plot(ax=ax_arr[1], color="c", linestyle='-')
ax_arr[1].set_title("Trend section")
pd.Series(data=decompose_model.seasonal, index=x).plot(ax=ax_arr[2], color="g", linestyle='-')
ax_arr[2].set_title("Seasonal section")
pd.Series(data=decompose_model.resid, index=x).plot(ax=ax_arr[3], color="r", linestyle='-')
ax_arr[3].set_title("Residual section")
7、子圖合併一個圖,不知道數量
lens = len(all_sub_graphs)
b = a = int(math.sqrt(lens))
if a*a < lens:
b = b+1
plot = plt.subplot(a, b, i+1)
8、線條顏色和類型
plt.plot(y, color='b', marker='o')
plt.plot(y, color='b', linestyle='-')
linestyle,marker可選參數參考:https://www.cnblogs.com/darkknightzh/p/6117528.html
9、matplotlib去掉座標軸刻度
ax.set_axis_off()
ax.set_xticks([])
ax.set_yticks([])
10、label圖例有中文
plt.rcParams['font.sans-serif']=['SimHei'] # 用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False # 用來正常顯示負號
# 有中文出現的情況,需要u'內容'
11、設置座標軸
ax = plt.gca()
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
ax.set_xlim(xmin, xmax) # 設置座標軸範圍
12、隨機顏色
def random_color():
color_arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
color = ""
for i in range(6):
color += color_arr[random.randint(0, 14)]
return "#"+color
13、圖例位置
plt.legend(handles = [l1, l2], labels = ['a', 'b'], loc = 'best')
除'best',另外loc屬性有:'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'
14、解決linux圖片中文亂碼
plt.rcParams['font.sans-serif'] = ['simhei'] # 用來正常顯示中文標籤
還不行就:
import os
from matplotlib import font_manager as fm, rcParams
fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "D:/Anaconda3/Lib/site-packages/matplotlib\mpl-data/fonts/ttf/simhei.ttf") # 需要提前下好字體庫
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title(u'中文出來This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This 急急急 the default font', fontproperties=prop)
plt.savefig("chinese.png")
此時圖例:
plt.legend(loc="best", prop=prop)
15、畫垂直虛線
vlines(x, ymin, ymax)
hlines(y, xmin, xmax)
plt.vlines(x-values, -5, 100, colors="#808080", linestyles="dashed", label="baseline")
plt.hlines(up_threshold, x[0], x[-1], colors="r", linestyles="dashed") # 上線
plt.hlines(low_threshold, x[0], x[-1], colors="r", linestyles="dashed") # 下線
16、直方圖畫法
plt.hist(data, color='b', alpha=.7)
17、圖例legend在圖外的畫法
ax1 = plt.gca()
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width, box.height* 0.8])
ax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12), ncol=3)
18、將Matplotlib圖形保存爲全屏圖像
manager = plt.get_current_fig_manager()
manager.window.showMaximized()
19、tight_layout調整子圖參數
tight_layout會自動調整子圖參數,調整子圖之間的間隔來減少堆疊,使之填充整個圖像區域。關鍵字參數pad
、w_pad
或者h_pad
,這些參數圖像邊界和子圖之間的額外邊距。邊距以字體大小單位規定。
plt.tight_layout(pad=0.5, w_pad=0.5, h_pad=2.0)
20、圖片輸出方式
plt.savefig("fig.png") # 輸出方式1: 將圖像存爲一個png格式的圖片文件
plt.show() # 輸出方式2: 在窗口中顯示這幅圖像
tight_layout在plt.savefig的調用方式相對比較穩定,我們將plt.show()函數替換爲plt.savefig函數,替換後會在本地另外爲png圖片,該圖片中子圖填充了整個圖像區域。
plt.savefig('fig.png', bbox_inches='tight') # 替換 plt.show()