带有值图、Pandas 和 MatPlotLib 的月、年

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

Month,Year with Value Plot,Pandas and MatPlotLib

pythonpandasmatplotlib

提问by Sriram Arvind Lakshmanakumar

i have DataFrame with Month,Year and Value and i want to do a TimeSeries Plot.

我有带月、年和值的 DataFrame,我想做一个时间序列图。

Sample:

样本:

month   year    Value
12      2016    0.006437804129357764
1       2017    0.013850880792606646
2       2017    0.013330349031207292
3       2017    0.07663058273768052
4       2017    0.7822831457266424
5       2017    0.8089573099244689
6       2017    1.1634845000200715

im trying to plot this Value data with Year and Month, Year and Month in X-Axis and Value in Y-Axis.

我试图用 X 轴中的年和月、年和月以及 Y 轴中的值来绘制此值数据。

回答by Joe

One way is this:

一种方法是这样的:

import pandas as pd
import matplotlib.pyplot as plt

df['date'] = df['month'].map(str)+ '-' +df['year'].map(str)
df['date'] = pd.to_datetime(df['date'], format='%m-%Y').dt.strftime('%m-%Y')
fig, ax = plt.subplots()
plt.plot_date(df['date'], df['Value'])
plt.show()

enter image description here

在此处输入图片说明

回答by fernandezcuesta

You need to set a DateTimeindex for pandas to properly plot the axis. A one line modification for your dataframe (assuming you don't need yearand monthanymore as columns and that first day of each month is correct) would do:

您需要DateTime为Pandas设置索引以正确绘制轴。对您的数据框进行一行修改(假设您不再需要year并且month不再作为列并且每个月的第一天是正确的)将执行以下操作:

df.set_index(pd.to_datetime({
    'day': 1,
    'month': df.pop('month'),
    'year': df.pop('year')
}), inplace=True)

df.Value.plot()