簡體   English   中英

圖例標簽未在python中添加多個圖

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

我想讀取5個csv文件。 我有以下函數,分別繪制圖形,我想在每個圖形中添加圖例。 但是,我收到此警告,即使我在函數中添加了標簽,也不會將圖例添加到圖例中。

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

我們如何使圖例顯示在情節中?

lebel時設置lebel參數,並使用handle制作圖例。 嘗試這樣寫:

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