I wanted to read 5 csv
files. 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. 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="->"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.