如何根据来自多列的数据在 Pandas Python 中的一个图中绘制多条线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40071096/
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 02:13:27  来源:igfitidea点击:

How to plot multiple lines in one figure in Pandas Python based on data from multiple columns?

pythonpandasmatplotlibplot

提问by Jolie

I have a dataframe with 3 columns, like this:

我有一个包含 3 列的数据框,如下所示:

df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]

how can I plot a line for A, B and C, where it shows how their weight develops through the years. So I tried this:

我如何为 A、B 和 C 绘制一条线,它显示了它们的体重多年来的发展情况。所以我试过这个:

df.groupby("euro").plot(x="year", y="MKM")

However, I get multiple plots and that is not what I want. I want all those plots in one figure.

但是,我得到了多个图,这不是我想要的。我希望所有这些情节都集中在一个数字中。

采纳答案by Angus Williams

Does this produce what you're looking for?

这是否会产生您正在寻找的东西?

import matplotlib.pyplot as plt
fig,ax = plt.subplots()

for name in ['A','B','C']:
    ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)

ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')

enter image description here

在此处输入图片说明