1. 程式人生 > 實用技巧 >python中用matplotlib.pyplot.subplots畫共享座標曲線圖

python中用matplotlib.pyplot.subplots畫共享座標曲線圖

注:(1)控制座標軸顯示刻度用到了庫:matplotlib.ticker,可能需要安裝一下(如果小夥伴有更好的方法,可以留言交流一下)

(2)主要用到的函式matplotlib.pyplot.subplots,別忘了加“s”

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

from2 = FormatStrFormatter('%1.2f')
from4 = FormatStrFormatter('%1.4f')

time = np.linspace(0,6,100)                  #生成兩個函式
data1
= np.cos(time) data2 = np.sin(time) fig = plt.figure() #宣告畫布 p1, p2 = fig.subplots(2,1, sharex = True, sharey = False) #設定共享座標軸 2:兩行,1:一列,sharex:共享X軸,sharey:共享Y軸 plt.subplots_adjust(wspace = 0, hspace = 0 ) #wspace:圖間的行距離, hspace:圖間的列距離 p1.grid(linestyle = '
--') #設定線型 在圖中畫格網 - 實線 -- 虛線 -. 點劃線 : 點線 p1.yaxis.set_major_formatter(from2) #用來控制座標軸顯示的刻度位數 p2.yaxis.set_major_formatter(from4) p1.set_title('Plot') p1.set_ylabel('Cos', fontsize=12) #設定座標軸名字 p2.set_ylabel('Sin', fontsize=12) p2.set_xlabel('Time(s)
', fontsize=12) p1.plot(time, data1, 'r-', label='Data1') #plot:畫曲線圖,scatter:畫散點圖,bar:柱狀圖 p2.plot(time, data2, 'k-', label='Data2') #b: blue,g: green,r: red,c: cyan,m: magenta,y: yellow,k: black,w: white #lable:legend的顯示 p1.legend(loc = 'upper right') #ncol:列 控制顯示標籤的位置 p2.legend(loc = 'upper right') plt.show()

效果圖: