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在運行過程中,查看每個變量的操作(show variables)
這篇文章主要介紹了使用Pycharm在運行過程中,查看每個變量的操作(show variables),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python調(diào)用graphviz繪制結構化圖形網(wǎng)絡示例
今天小編就為大家分享一篇Python調(diào)用graphviz繪制結構化圖形網(wǎng)絡示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
python實現(xiàn)簡單socket程序在兩臺電腦之間傳輸消息的方法
這篇文章主要介紹了python實現(xiàn)簡單socket程序在兩臺電腦之間傳輸消息的方法,涉及Python操作socket的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
使用python實現(xiàn)strcmp函數(shù)功能示例
這篇文章主要介紹了使用python實現(xiàn)strcmp函數(shù)功能的示例,需要的朋友可以參考下2014-03-03

