日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

matplotlib?雙y軸繪制及合并圖例的實現代碼_python

作者:華小電 ? 更新時間: 2022-11-28 編程語言

Matplotlib 是 Python 的繪圖庫,它能讓使用者很輕松地將數據圖形化,并且提供多樣化的輸出格式。

Matplotlib 可以用來繪制各種靜態,動態,交互式的圖表。

Matplotlib 是一個非常強大的 Python 畫圖工具,我們可以使用該工具將很多數據通過圖表的形式更直觀的呈現出來。

Matplotlib 可以繪制線圖、散點圖、等高線圖、條形圖、柱狀圖、3D 圖形、甚至是圖形動畫等等。

下面看下matplotlib 雙y軸繪制及合并圖例。

1.雙y軸繪制 關鍵函數:twinx()

# -*- coding: utf-8 -*-
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib import rc
 rc('mathtext', default='regular') 

 time = np.arange(10)
 temp = np.random.random(10)*30
 Swdown = np.random.random(10)*100-10
 Rn = np.random.random(10)*100-10 

 fig = plt.figure()
 ax = fig.add_subplot(111)
 ax.plot(time, Swdown, '-', label = 'Swdown')
 ax.plot(time, Rn, '-', label = 'Rn')
 ax2 = ax.twinx()
 ax2.plot(time, temp, '-r', label = 'temp')
 ax.legend(loc=0)
 ax.grid()
 ax.set_xlabel("Time (h)")
 ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
 ax2.set_ylabel(r"Temperature ($^circ$C)")
 ax2.set_ylim(0, 35)
 ax.set_ylim(-20,100)
 ax2.legend(loc=0)

合并圖例

# -*- coding: utf-8 -*-
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib import rc
 rc('mathtext', default='regular') 

 time = np.arange(10)
 temp = np.random.random(10)*30
 Swdown = np.random.random(10)*100-10
 Rn = np.random.random(10)*100-10
 

 fig = plt.figure()
 ax = fig.add_subplot(111) 

 lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
 lns2 = ax.plot(time, Rn, '-', label = 'Rn')
 ax2 = ax.twinx()
 lns3 = ax2.plot(time, temp, '-r', label = 'temp')
 

 # added these three lines
 lns = lns1+lns2+lns3
 labs = [l.get_label() for l in lns]
 ax.legend(lns, labs, loc=0)
 

 ax.grid()
 ax.set_xlabel("Time (h)")
 ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
 ax2.set_ylabel(r"Temperature ($^circ$C)")
 ax2.set_ylim(0, 35)
 ax.set_ylim(-20,100)

使用Figure.legend()

# -*- coding: utf-8 -*-
 import numpy as np
 import matplotlib.pyplot as plt 

 x = np.linspace(0,10)
 y = np.linspace(0,10)
 z = np.sin(x/3)**2*98 

 fig = plt.figure()
 ax = fig.add_subplot(111)
 ax.plot(x,y, '-', label = 'Quantity 1') 

 ax2 = ax.twinx()
 ax2.plot(x,z, '-r', label = 'Quantity 2')
 fig.legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)
 

 ax.set_xlabel("x [units]")
 ax.set_ylabel(r"Quantity 1")
 ax2.set_ylabel(r"Quantity 2")

原文鏈接:https://www.cnblogs.com/conpi/p/16812311.html

欄目分類
最近更新