[英]Python: Plot Pandas DataFrame with manually assigned legend
I am trying to manually assign a legend to a plot that is based on a Pandas DataFrame.我正在尝试为基于 Pandas DataFrame 的绘图手动分配图例。 I thought using the
label
keyword of the pd.plot
function should be the way to go.我认为使用
pd.plot
函数的label
关键字应该是pd.plot
的方法。 However, I am struggling...然而,我在挣扎……
Here's my toy example:这是我的玩具示例:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create dummy dataframe
df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
index=pd.date_range('20190101', periods=20),
columns=list('AB'))
# Create plot
fig, ax1 = plt.subplots(1, 1)
ax1.plot(df, label=['line1', 'line2'])
ax1.legend()
I assume you mean plotting directly from pd.DataFrame
.我假设您的意思是直接从
pd.DataFrame
绘图。 The pd.DataFrame.plot()
function returns an matplotlib.axes.Axes
object, which you can use to manipulate a legend. pd.DataFrame.plot()
函数返回一个matplotlib.axes.Axes
对象,您可以使用它来操作图例。
import numpy as np
import pandas as pd
# Create dummy dataframe
df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
index=pd.date_range('20190101', periods=20),
columns=list('AB'))
# Create plot directly from pandas.DataFrame
ax = df.plot()
ax.legend(['line1', 'line2'])
gives给
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.