Matplotlib使用方法大全
一:繪制基礎的折線圖
1 #encoding:utf-8 2 import matplotlib.pyplot as plt 3 4 def test1(): 5 # 基礎折線圖繪制 6 # 繪制(0,0),(1,1),(2,1),(3,3)四個點連成的折線 7 x = [0, 1, 2, 3] 8 y = [0, 1, 1, 3] 9 plt.plot(x, y) 10 plt.show()
二: 修改折線圖顏色或者線的形狀
def test2(): # 修改折線圖的顏色 / 線的形狀 x = [0, 1, 2, 3] y = [0, 1, 1, 3] plt.plot(x, y, "r") # 修改顏色, rgb=紅綠藍 plt.plot(x, y, "--") # 修改線的形狀為虛線, 默認為折線"-", "o" 為點 “^" 為三角 plt.plot(x, y, "g--") # 一起修改為綠色虛線 plt.axis([1, 6, 0, 5]) # 修改坐標軸x刻度顯示 plt.show()
三:只傳入一維數據
plt.plot(x, y)接收點集(x, y),當只輸入一維數據的時候默認當做y坐標軸處理,x坐標軸默認為為[0,1,2....]
def test3(): y = [1, 1, 1, 1] plt.plot(y, "ro") plt.show()
四:當傳入list時也會轉成numpy.array(性能會好些)
import numpy as np def test4(): t1 = [1, 5, 1, 5] t2 = np.array([5, 1, 5, 1]) plt.plot(t1, "g-") plt.plot(t2, "ro") plt.show()
五:一張圖中顯示多張圖表
在例4中分別使用了兩次plt.plot()進行加載,可以用一條語句
plt.plot(t1, "b--",t2, "r--")
def test5(): # 在一張圖表中顯示多個圖表 x1 = [1, 2, 3, 4] y1 = [1, 2, 3, 4] x2 = [2, 4, 6, 8] y2 = [4, 8, 12, 16] plt.plot(x1, y1, "r-", x2, y2, "g--") plt.show()
六:繪制標准函數sin()與cos()
def test6(): # 繪制標准函數曲線: sin()與cos() # 繪制f(x)=sin(x) 和g(x)=cos(x) 在x∈[0,20]中的圖像 x = np.arange(0, 20, 0.01) plt.plot(x, np.sin(x), "r-", x, np.cos(x), "g--") # x坐標軸區間: [0, 20] y坐標軸區間: [-3, 3] plt.axis([0, 20, -3, 3]) plt.show()
七: 顯示背景網格線
def test7(): x = np.arange(0, 20, 0.01) plt.plot(x, x**2) # 設置是否顯示網格線 plt.grid(True) plt.show()
八: 對圖表進行標注及對文本屬性的設置
def test8(): # 增加標注 x = np.arange(0, 20, 0.01) plt.plot(x, x**2) # 設置x, y坐標軸的名稱
# 對x坐標軸的文本內容進行設置
plt.xlabel("Money Earned", color="r", fontsize=20) # plt.xlabel("Money Earned") plt.ylabel("Consume Level") # 顯示網格 plt.grid(True) # 增加標題 plt.title("Figure.1") # 圖內文字 # 指定x坐標軸和y坐標軸,文字本身 plt.text(2.5, 100, "TEXT1") # 箭頭指示 # 指定文字, 箭頭指定方向,文字顯示的坐標, 箭頭的屬性 plt.annotate("max value", xy=(20, 400), xytext=(12.5, 400), arrowprops=dict(facecolor="black", shrink=0.05),) plt.show()
對文本屬性設置參數簡介(https://matplotlib.org/api/text_api.html#matplotlib.text.Text)
常用參數介紹:
九: 設置曲線屬性
plt.plot()返回matplotlib.lines.Line2D, 可以通過變量獲得並修改曲線Line2D的屬性
def test9(): # 設置曲線屬性 # plt.plot()返回matplotlib.lines.Line2D,可以通過變量獲得並修改曲線Line2D的屬性 x = np.arange(0, 10, 0.01) line1, line2 = plt.plot(x, np.sin(x), "-", x, np.cos(x), "--") plt.setp(line1, color="r", linewidth="11.0") # 設置曲線的寬度 plt.show()
十: 繪制圖形: 圓形,矩形,橢圓
import matplotlib.patches as patches def test10(): # 繪制圓形 fig = plt.figure() ax1 = fig.add_subplot(111, aspect="equal") # 1X1一張圖中的第一張, equal為等寬顯示 rec = patches.Rectangle((0, 0), 8, 4) # 頂點坐標(0,0) 寬w=8, 高h=4 cir = patches.Circle((8, 8), 2) # 圓心坐標(8,8) 半徑r ell = patches.Ellipse((2, 8), 6, 3) # 橢圓左頂點坐標(2, 8) 長軸6 短軸3 ax1.add_patch(rec) ax1.add_patch(cir) ax1.add_patch(ell) plt.plot() plt.show()
十一: 繪制標准正態分布-直方圖
plt.hist() 繪制直方圖
def test11(): # 繪制直方圖-標准正態分布 mu, sigma = 0, 1 x = np.random.normal(mu, sigma, 10000) # x: 一維數組, : 直方圖的柱數,默認為10, facecolor: 直方圖顏色 alpha: 透明度 # 返回值: n:直方圖向量 bins: 返回各個bin的區間范圍 patches: 以list形式返回每個bin里面包含的數據 plt.hist(x, bins=100, facecolor="g", alpha=0.75) plt.text(-3, 250, r'$\mu=0,\ \sigma=1$') plt.grid(True) plt.show()
十二::繪制散點圖
plt.scatter() 繪制散點圖
def test12(): # 繪制散點圖 # x: x坐標軸集合 y: y坐標軸集合 c : 散點的顏色數目 s: 散點的大小數目 alpha: 透明度 x = np.random.normal(0, 1, 1000) y = np.random.normal(0, 1, 1000) c = np.random.rand(1000) s = np.random.rand(100)*100 # 100種大小 plt.scatter(x, y, c=c, s=s, alpha=0.5) plt.grid(True) plt.show()
十三: 顯示多個圖表
方法一:
def test13(): # 顯示多個圖表 names = ['Anime', 'Comic', 'Game'] values = [30, 10, 20] plt.subplot(221) # 構建2X2張圖中的第一張子圖 plt.bar(names, values) # 統計圖 plt.subplot(222) plt.scatter(names, values) plt.subplot(223) plt.plot(names, values) plt.suptitle("三種圖顯示", fontname="SimHei") plt.show()
方法二:
def test14(): # 上述是每次構造一個子圖,然后在子圖中繪制.也可以先構造所有的子圖,再通過下標指定在哪張子圖中繪制 fig, axes = plt.subplots(2, 2) names = ['Anime', 'Comic', 'Game'] values = [30, 10, 20] axes[0, 1].plot(names, values) axes[1, 0].bar(names, values) axes[1, 1].scatter(names, values) plt.show()
十四:子圖間距的調整
def test15(): # 調整子圖間隔 # #構造2x2的子圖,子圖共享x,y軸 fig, axes = plt.subplots(2, 2, sharex=True, sharey=True) for i in range(2): for j in range(2): axes[i, j].hist(np.random.rand(500), bins=100, alpha=0.7, color="k") plt.subplots_adjust(hspace=0, wspace=0) # 修改內部的寬,高間距為0 plt.show()
十五: 繪制柱狀圖
垂直柱狀圖plt.bar(names,values)
水平柱狀圖plt.barh(names,values)
def test16(): # 垂直柱狀圖 plt.bar(name, values) # 水平柱狀圖 plt.barh(name, values) x = np.random.randint(1, 10, 8) label = list("abcdefgh") plt.subplot(221) plt.bar(label, x) plt.subplot(222) plt.barh(label, x) plt.show()
pd.DataFrame.plot.bar()繪制柱形圖
import pandas as pd def test17(): x = np.random.randint(1, 10, 8) y = np.random.randint(1, 10, 8) # index為分類, columns為數據的柱狀圖 data = pd.DataFrame([x, y], index=["X", "Y"], columns=list("abcdefgh")) # data.plot.bar() data.transpose().plot.bar() # data.transpose()轉置 plt.show()