【问题标题】:How to change the legend location for pandas subplots如何更改熊猫子图的图例位置
【发布时间】:2021-12-28 14:57:13
【问题描述】:

我正在尝试创建一个包含大量子图的熊猫图,在本例中为 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()

但我无法设置图例的位置,因此所有图表都清晰易读,这是当前外观的示例:

我已经在另一个堆栈溢出帖子中尝试了这两种解决方案 - Set the legend location of a pandas plot

...但实际上都没有工作。我也尝试按照这个答案使用tight_layout(),但它同样难以辨认-Plot pandas dataframe with subplots (subplots=True): Place legend and use tight layout

任何人都可以提供有关如何放置具有如此多图表的图表的图例并仍然保持可读性的任何指导吗?

【问题讨论】:

    标签: python pandas matplotlib plot legend


    【解决方案1】:
    • pandas.DataFrame.plotsubplots=True 返回 numpy.ndarraymatplotlib.axes.Axes
    • 访问每个子图axes 的最简单方法是展平数组,然后遍历每个子图。
    • 使用How to put the legend out of the plot 的答案将图例放置在适当的位置。
    • 其他axes 级别的修改可以使用标准的matplotlib 面向对象方法(即以ax. 开头的方法)在循环内进行。
    • 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()
    

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 2020-08-30
      相关资源
      最近更新 更多