【问题标题】:Matplotlib Legend Wont Show UpMatplotlib 传奇不会出现
【发布时间】:2020-07-08 19:29:59
【问题描述】:

我尝试的每个选项都没有为我的情节显示图例。请帮忙。这是代码,并且在我的所有输入都是简单的 NumPy 数组的情况下,该图可以正常工作。添加图例功能时,角落会出现一个小框,因此我知道该指令正在运行,但其中没有任何内容。我正在使用 Jupyter Notebook,我的其他尝试显示在 # 之后。谁能找到漏洞:

import pandas as pd
import matplotlib.pyplot as plt

ratios = ['Share Price', 'PEG', 'Price to Sales']
final_z_scores = np.transpose(final_z_scores)
print(final_z_scores)

fig = plt.figure(figsize=(6,4))

#plt.plot(ratios, final_z_scores[0], ratios, final_z_scores[1], ratios, final_z_scores[2])
first = plt.plot(ratios, final_z_scores[0])
second = plt.plot(ratios, final_z_scores[1])

#ax.legend((first, second), ('oscillatory', 'damped'), loc='upper right', shadow=True)
ax.legend((first, second), ('label1', 'label2'))
plt.xlabel('Ratio Types')
plt.ylabel('Values')
plt.title('Final Comparisons of Stock Ratios')
plt.legend(loc='upper left')

plt.plot()
plt.show()

【问题讨论】:

    标签: python matplotlib legend legend-properties


    【解决方案1】:

    在不指定handleslabels 的情况下调用plt.legend() 明确遵守here 概述的此调用签名的描述:

    当您不传递任何额外参数时,将自动确定要添加到图例的元素。

    在这种情况下,标签取自艺术家。您可以在创建艺术家时指定它们,也可以通过在艺术家上调用 set_label() 方法来指定它们:

    因此,为了在您的示例中自动填充图例,您只需为不同的图分配标签:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    ratios = ['Share Price', 'PEG', 'Price to Sales']
    final_z_scores = np.transpose(final_z_scores)
    
    fig = plt.figure(figsize=(6,4))
    first = plt.plot(ratios, final_z_scores[0], label='label1')
    second = plt.plot(ratios, final_z_scores[1], label='label2')
    
    plt.xlabel('Ratio Types')
    plt.ylabel('Values')
    plt.title('Final Comparisons of Stock Ratios')
    plt.legend(loc='upper left')
    
    # Calling plt.plot() here is unnecessary 
    plt.show()
    

    【讨论】:

      【解决方案2】:

      您可以更改在plt.plot() 调用中分配标签的方式:

      first = plt.plot(ratios, final_z_scores[0], label='label1')
      second = plt.plot(ratios, final_z_scores[1], label='label2')
      

      然后您可以将您的图例调用修改为:plt.legend()

      【讨论】:

        【解决方案3】:

        考虑到 legend 属性采用列表作为参数。 试试这样的:

        plt.legend(['first stock name', 'second stock name'])
        

        【讨论】:

          【解决方案4】:

          看起来您正在将面向对象 (OO) 的绘图风格与 PyPlot 风格混合在一起。 如果你使用 OO 风格,你从定义 ax 开始:

          fig, ax = plt.subplots()
          

          而对于 PyPlot 样式,您可以直接使用 plt.plot(),而无需先定义 ax

          在你的代码中你没有定义 ax,你使用 PyPlot 风格:

          first = plt.plot(ratios, final_z_scores[0])
          second = plt.plot(ratios, final_z_scores[1])
          

          要解决您的问题,请继续使用 PyPlot 样式:

          first = plt.plot(ratios, final_z_scores[0], label='label1')
          second = plt.plot(ratios, final_z_scores[1], label='label2')
          ...
          plt.legend()
          plt.plot()
          

          根本不要使用ax.legend((first, second), ('label1', 'label2')) - 这是一个你一开始没有定义的对象

          这里很好地解释了 OO 和 PyPlot 风格的区别: https://matplotlib.org/3.2.0/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py

          【讨论】:

          • 太棒了。这解决了问题。谢谢。
          【解决方案5】:

          dataframe.columns.tolist() 替换为您的列列表。希望对您有所帮助:

          ax.legend(dataframe.columns.tolist())
          
          
          def plot_df(dataframe,x_label:str,y_label:str, title:str="" ):
              """
              requires plt.show() to display graph
              """
          
              
              
              fig,ax = plt.subplots(figsize=(15, 10))
             
              ax.set_xlabel(x_label)
              ax.set_ylabel(y_label)
              if title:
                  ax.set_title(title)
          
              hourlocator = md.HourLocator(interval = 1)
          
              # Set the format of the major x-ticks:
              majorFmt = md.DateFormatter('%H:%M')  
          
              ax.xaxis.set_major_locator(hourlocator)
              ax.xaxis.set_major_formatter(majorFmt)
              ax.plot(dataframe.index,dataframe.values)
              ax.legend(dataframe.columns.tolist())
              fig.autofmt_xdate() #makes 30deg tilt on tick labels
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-10-20
            • 1970-01-01
            • 2013-10-27
            • 1970-01-01
            • 1970-01-01
            • 2013-08-22
            • 1970-01-01
            • 2013-09-07
            相关资源
            最近更新 更多