简体   繁体   English

图例标签未在python中添加多个图

[英]Legend label is not adding for multiple plots in python

I wanted to read 5 csv files. 我想读取5个csv文件。 I have the following function which plots the graphs separately and I wanted to add a legend to to each plot. 我有以下函数,分别绘制图形,我想在每个图形中添加图例。 However, I am getting this warning the legend is not being added to the plots even if i have a label added to my function. 但是,我收到此警告,即使我在函数中添加了标签,也不会将图例添加到图例中。

UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "

import pandas as pd
import matplotlib.pyplot as plt


df1 = pd.read_csv('test1.csv')
df2 = pd.read_csv('test2.csv')
df3 = pd.read_csv('test3.csv')
df4 = pd.read_csv('test4.csv')
df5 = pd.read_csv('test5.csv')


def runplot(df, title, label):   
    rows, cols = df.shape

    fig, ax = plt.subplots()
    ax.plot(df['price'].values, df['cost'].values)
    ax.legend()


    plt.title(title)
    plt.annotate('test!', 
                 xy=(rows, df.ix[rows-1,'cost']),  
                 xycoords='data',
                 xytext=(-30,30),
                 textcoords='offset points',
                 arrowprops=dict(arrowstyle="->"))


runplot(df1, 'test1.csv', label='test1')
runplot(df2, 'test2.csv', label='test2')
runplot(df3, 'test3.csv', label='test3')
runplot(df4, 'test4.csv', label='test4')
runplot(df5, 'test5.csv', label='test5')

How can we make the legend show in the plots? 我们如何使图例显示在情节中?

Set lebel argument when plot and use handle to make a legend. lebel时设置lebel参数,并使用handle制作图例。 Try to write like this: 尝试这样写:

def runplot(df, title, label):   
    rows, cols = df.shape

    fig, ax = plt.subplots()
    line1, = ax.plot(df['price'].values, df['cost'].values, label=label)
    ax.legend(handles=[line1])

    plt.title(title)
    plt.annotate('test!', 
                 xy=(rows, df.ix[rows-1,'cost']),  
                 xycoords='data',
                 xytext=(-30,30),
                 textcoords='offset points',
                 arrowprops=dict(arrowstyle="->"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM