【问题标题】:No handles with labels found to put in legend error after plotting two plots on one chart在一张图表上绘制两个图后,没有发现带有标签的句柄出现图例错误
【发布时间】:2021-03-29 23:16:39
【问题描述】:

我正在逐月绘制一些特征,并突出显示其中的一些。在我添加高亮之前,图例可以自动显示,但现在它返回 No handles with labels found to put in legend 错误。

示例数据

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
highlight = ['A', 'B']
fig, ax = plt.subplots(figsize=(15, 5))
plt.plot(df.loc[:, ~df.columns.isin(highlight)], c='gray', alpha=0.5) 
plt.plot(df.loc[:, df.columns.isin(highlight)]) 
months = pd.date_range('2019-04-01','2019-08-01', freq='MS').strftime("%Y-%m").tolist()
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
z = ax.set_xticklabels(months, rotation=45)

我猜想在一张图表上绘制两个图会导致此问题,但不知道如何解决。我不想手动指定图例。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:
    • 使用pandas.DataFrame.plot 而不是plt.plot
      • 这可确保将列标题作为标签正确分配给正确的行
      • 它返回一个matplotlib.axes.Axes 或一个numpy.ndarray
    • 这个例子使用pandas v1.2.3
    import pandas as pd
    import matplotlib.pyplot as plt
    
    ax = df.loc[:, df.columns.isin(highlight)].plot(figsize=(15, 5))
    df.loc[:, ~df.columns.isin(highlight)].plot(c='gray', alpha=0.5, ax=ax)
    
    plt.legend(title='column labels', loc='center left', bbox_to_anchor=(1.0, 0.5))
    plt.show()
    

    【讨论】:

      【解决方案2】:

      只需切换 plt.plot() 语句的顺序并像这样明确声明图例项:

      df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
      highlight = ['A', 'B']
      
      fig, ax = plt.subplots(figsize=(15, 5))
      plt.plot(df.loc[:, df.columns.isin(highlight)])
      plt.plot(df.loc[:, ~df.columns.isin(highlight)], c='gray', alpha=0.5)
      months = pd.date_range('2019-04-01','2019-09-01', freq='MS').strftime("%Y-%m").tolist()
      plt.legend(list('ABCD'),loc='center left', bbox_to_anchor=(1.0, 0.5))
      z = ax.set_xticklabels(months, rotation=45)
      plt.show()
      

      【讨论】:

        【解决方案3】:

        您可以通过在plt.plot(...,label=...) 时添加标签参数来消除该错误,No handles with labels found to put in legend linechart 的解决方案相同。

        运行您的代码时,我还收到另一个错误,但这不是问题和答案的一部分。

        没有发现带有标签的句柄放在图例中。 :13: UserWarning: FixedFormatter 应该 只能与 FixedLocator z = 一起使用 ax.set_xticklabels(months, rotation=45)

        我添加了 label='test' 和 label='test2' 作为开始。

        import pandas as pd
        import numpy as np
        import matplotlib.pyplot as plt
        
        df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
        highlight = ['A', 'B']
        
        fig, ax = plt.subplots(figsize=(15, 5))
        plt.plot(df.loc[:, ~df.columns.isin(highlight)], c='gray', alpha=0.5, label='test')
        plt.plot(df.loc[:, df.columns.isin(highlight)], label='test2')
        months = pd.date_range('2019-04-01','2019-08-01', freq='MS').strftime("%Y-%m").tolist()
        plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
        z = ax.set_xticklabels(months, rotation=45)
        

        错误消失了。

        剩下的只是无论如何都存在且与问题无关的错误:

        <ipython-input-78-5f152143ed24>:13: UserWarning: FixedFormatter should only be used together with FixedLocator
          z = ax.set_xticklabels(months, rotation=45)
        

        【讨论】:

          猜你喜欢
          • 2021-05-25
          • 2019-05-23
          • 2020-05-06
          • 2021-10-24
          • 2020-03-20
          • 1970-01-01
          • 1970-01-01
          • 2020-04-08
          • 1970-01-01
          相关资源
          最近更新 更多