總結用matplotlib畫圖遇到的一些問題
1. 匯入包創建圖
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig = plt.figure()
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.show()
結果如下:

2. 設定漢字
如果圖的標題、軸標簽、刻度等需要漢字,直接畫圖漢字會亂碼,在程式開頭添加以下兩行代碼即可,
mpl.rcParams['font.sans-serif'] = [u'SimHei'] # 中文字體可修改
mpl.rcParams['axes.unicode_minus'] = False
設定圖中中文標題
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
plt.title("中文標題")
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.show()

3. 設定軸標簽
plt.xlabel("x軸標簽")
plt.ylabel("y軸標簽")
添加軸標簽并重新繪制:
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
plt.title("中文標題")
# 刻度也可用漢字
plt.plot(["刻度1", "刻度2", "刻度3", "刻度4"], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.xlabel('x軸軸標簽')
plt.ylabel('y軸軸標簽')
plt.show()
結果如下:

4. 刻度線內向
matplotlib畫圖時默認刻度線朝向外側,如果需要刻度線內向,添加代碼:
plt.rcParams['xtick.direction'] = 'in' # 刻度線內向
plt.rcParams['ytick.direction'] = 'in'
重新繪制
fig = plt.figure()
plt.rcParams['xtick.direction'] = 'in' # 刻度線內向
plt.rcParams['ytick.direction'] = 'in'
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.show()
結果如下:

5. 添加圖例
plt.plot(label='圖例') # 圖例名稱
plt.legend()
實體展示:
fig = plt.figure()
plt.rcParams['xtick.direction'] = 'in' # 刻度線內向
plt.rcParams['ytick.direction'] = 'in'
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r', label='圖例1')
plt.plot([2, 4, 6, 9], [2, 5, 8, 9], marker='s', mec='g', mfc='g', label='圖例2')
plt.legend(loc='upper left')
plt.show()
結果如下:

持續更新…
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/256381.html
標籤:python
