如何更改 pandas 个子图的图例位置

How to change the legend location for pandas subplots

我正在尝试创建一个包含大量子图的 pandas 图,在本例中为 58 个。数据是宽格式的,格式类似于:

df = 

Date It1 It2 It3... Itn 
0    x    x   x      n
1    x    x   x      n
2    x    x   x      n
3    x    x   x      n

我已经能够创建情节 pandas 情节没有问题:

rows = df.shape[1]//2
df.plot(legend = True, subplots = True, layout = (rows,5), grid=True, title="Labs", sharex=True, sharey=False,figsize=(12,32),)
plt.show()

但是我在设置图例位置时遇到问题,因此所有图表都清晰可见,这是当前外观的示例:

我在另一个堆栈溢出中尝试了两种解决方案 post -

...但实际上都不起作用。我也尝试根据这个答案使用 tight_layout() 但它同样难以辨认 -

任何人都可以提供任何指导,说明如何在包含这么多图表的图表上放置图例并保持其可读性吗?

  • pandas.DataFrame.plot with subplots=True returns a numpy.ndarray of matplotlib.axes.Axes
  • 访问每个子图的最简单方法 axes 是展平数组,然后遍历每个子图。
  • 使用 How to put the legend out of the plot 的答案将图例放在适当的位置。
  • 可以使用标准的 matplotlib 面向对象方法(即以 ax. 开头的方法)在循环内进行其他 axes 级修改。
  • figsize 必须根据行数和列数进行调整。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# # sinusoidal sample data
sample_length = range(1, 15+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])

# plot the data with subplots and assign the returned array
axes = df.plot(subplots=True, layout=(3, 5), figsize=(25, 15))

# flatten the array
axes = axes.flat  # .ravel() and .flatten() also work

# extract the figure object to use figure level methods
fig = axes[0].get_figure()

# iterate through each axes to use axes level methods
for ax in axes:
    
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.10), frameon=False)
    
fig.suptitle('Sinusoids of Different Frequency', fontsize=22, y=0.95)
plt.show()