Matplotlib多子圖使用一個圖例的實現(xiàn)
更新時間:2023年08月16日 10:04:05 作者:Threetiff
多子圖是Matplotlib中的一個功能,可以在同一圖形中創(chuàng)建多個子圖,本文主要介紹了Matplotlib多子圖使用一個圖例的實現(xiàn),感興趣的可以了解一下
1 所有子圖的圖例相同
利用函數(shù) fig.axe.get_legend_handles_labels() 得到圖的 line 和 label
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
for ax in fig.axes:
ax.plot([0, 10], [0, 10], label='linear')
# 使用最后一個子圖的圖例
lines, labels = fig.axes[-1].get_legend_handles_labels()
fig.legend(lines, labels, loc = 'upper center') # 圖例的位置,bbox_to_anchor=(0.5, 0.92),
plt.show()
2 所有的子圖圖例不同
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 501)
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
axes[0, 0].plot(x,np.sin(x),color = 'k',label="sin(x)")
axes[0, 1].plot(x,np.cos(x),color = 'b',label="cos(x)")
axes[1, 0].plot(x,np.sin(x) + np.cos(x),color = 'r',label="sin(x)+cos(x)")
axes[1, 1].plot(x,np.sin(x) - np.cos(x),color = 'm',label="sin(x)-cos(x)")
lines = []
labels = []
# 利用循環(huán)得到每一個子圖的圖例
for ax in fig.axes:
axLine, axLabel = ax.get_legend_handles_labels()
lines.extend(axLine)
labels.extend(axLabel)
fig.legend(lines, labels, loc = 'upper right') # 圖例的位置,bbox_to_anchor=(0.5, 0.92),
plt.show()
參考鏈接
到此這篇關于Matplotlib多子圖使用一個圖例的實現(xiàn)的文章就介紹到這了,更多相關Matplotlib多子圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Pycharm生成可執(zhí)行文件.exe的實現(xiàn)方法
這篇文章主要介紹了Pycharm生成可執(zhí)行文件.exe的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06
把Anaconda中的環(huán)境導入到Pycharm里面的方法步驟
這篇文章主要介紹了把Anaconda中的環(huán)境導入到Pycharm里面的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10
結(jié)合Python網(wǎng)絡爬蟲做一個今日新聞小程序
本篇文章介紹了我在開發(fā)過程中遇到的一個問題,以及解決該問題的過程及思路,通讀本篇對大家的學習或工作具有一定的價值,需要的朋友可以參考下2021-09-09

