4

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

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.

1

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

5 Comments

This is the approach i thought of doing, but didn't know about using map function.
not all the month-year is visible in the x-axis!, some are hidden, is due to the graph size?
You can try to rotate them with plt.xticks(rotation=90)
can u post the image?
Try adding: positions = [p for p in df['date']] labels = [l for l in positions] ax.set_xticks(positions) ax.set_xticklabels(labels)
1

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

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

df.Value.plot()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.