Matplotlib 传奇不会出现

Matplotlib Legend Wont Show Up

我尝试的每个选项都没有为我的情节显示图例。请帮忙。这是代码,绘图工作正常,我的所有输入都是简单的 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()

调用 plt.legend() 而不指定 handleslabels 明确遵守此调用签名的描述 here:

The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.

In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist:

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

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()

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

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

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

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

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

您似乎将面向对象 (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

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