如何在x轴上设置相同的值并在matplotlib中命名一组子批次

2024-04-25 05:01:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在matplotlib中创建了一个子图,我想在所有子图上设置相同的x轴值,即从0到20。还希望分别重命名每个子批次,或添加图例,以便为读者澄清每个子批次

`import matplotlib.pyplot as plt 
 import pandas as pd
 import numpy as np
 import itertools
 x =[1, 2, 3, 4, 5] 
 y =[2, 3, 3, 2, 3] 

 a =[1, 2, 3, 4, 5] 
 b =[2, 1, 0, 1, 0] 

 c =[1, 2, 3, 4, 5] 
 d =[2, 2, 4, 4, 1] 

 e =[1, 2, 3, 4, 5] 
 f =[2, 2, 8, 8, 2] 

 g =[1, 2, 3, 4, 5] 
 h =[2.5, 3, 4, 5, 5] 

 i =[1, 2, 3, 4, 5] 
 j =[4, 5, 5.5, 9, 0] 

 k =[1, 2, 3, 4, 5] 
 l =[10, 10, 10, 10, 10] 

 m =[1, 2, 3, 4, 5] 
 n =[15, 16, 17, 18, 16] 

 fig, axes = plt.subplots(4, 2) 

 axes[0, 0].plot(x, y, 'b--o') 
 axes[0, 1].plot(a, b, 'b--o') 
 axes[1, 0].plot(c, d, 'r--o') 
 axes[1, 1].plot(e, f, 'r--o') 
 axes[2, 0].plot(g, h, 'g--o') 
 axes[2, 1].plot(i, j, 'g--o') 
 axes[3, 0].plot(k, l, 'm--o')  
 axes[3, 1].plot(m, n, 'm--o') 

 fig.tight_layout() 

 plt.savefig('pq.png', dpi=300, bbox_inches='tight')

 plt.show()`

结果是:enter image description here


Tags: importpandasplotmatplotlibasfigplt重命名
1条回答
网友
1楼 · 发布于 2024-04-25 05:01:39

可以使用matplotlib.pyplot.setp为所有轴设置相同的x/y限制:

plt.setp(axes, ylim=(0, 20))

您可以使用label参数命名绘图:

axes[0, 0].plot(x, y, 'b o', label='x-y plot')

您可以使用figure.legend(或axis.legend)在图形上绘制图例(或在每个子地块上绘制图例):

# one legend on the figure
fig.legend()

或:

# one legend on subplot[0, 0]
axes[0, 0].legend()

相关问题 更多 >