pandas 在 pylab.plot 中使用数据框列名作为标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33021542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:00:37  来源:igfitidea点击:

Use dataframe column names as labels in pylab.plot

pythonpandasmatplotlibdataframelabels

提问by TPM

I would like to plot the data in a dataframe and have the column headers be the labels. I tried this:

我想在数据框中绘制数据并将列标题作为标签。我试过这个:

dfm.columns = ['a','b']
plot(dfm.cumsum(), label= dfm.columns.values)
legend(loc='upper left')

But got this:

但是得到了这个:

enter image description here

在此处输入图片说明

Instead of both lines being labeled ['a','b'], I'd like the blue line to be a and the green to be b using pylab

而不是两行都被标记为 ['a','b'],我希望蓝线是 a,绿色是 b 使用 pylab

回答by Leb

I think it's the way you have your data set up in part of the code you're not showing.

我认为这是您在未显示的部分代码中设置数据的方式。

Here's an example, I used df.plot()in this case.

这是一个例子,我df.plot()在这种情况下使用。

import pandas as pd
import random
import matplotlib.pyplot as plt

x = [random.randint(10,20) for r in range(100)]
y = [random.randint(0,10) for r in range(100)]

df = pd.DataFrame([x,y]).T #T for transpose

df.columns=['a','b']

df.plot(kind='line')

plt.legend(loc='upper left')

plt.show()

enter image description here

在此处输入图片说明

Edit

编辑

pylabversion

pylab版本

import pandas as pd
import random
import matplotlib.pylab as plt

x = [random.randint(10,20) for r in range(100)]
y = [random.randint(0,10) for r in range(100)]

df = pd.DataFrame([x,y]).T

plt.plot(df)

plt.legend(['a','b'],loc='upper left')

plt.show()