0

My dataframe is like this-

   Energy_MWh    Month
0   39686.82    1979-01
1   35388.78    1979-02
2   50134.02    1979-03
3   37499.22    1979-04
4   20104.08    1979-05
5   17440.26    1979-06

It goes on like this to the month 2015-12. So you can imagine all the data.

I want to plot a continuous graph with the months as the x-axis and the Energy_MWh as the y-axis. How to best represent this using matplotlib?

I would also like to know for my knowledge if there's a way to print 1979-01 as Jan-1979 on the x-axis and so on. Probably a lambda function or something while plotting.

kev
  • 2,741
  • 5
  • 22
  • 48

2 Answers2

0

Set Month as the index:

df.set_index('Month', inplace=True)

Convert the index to Datetime:

df.index = pd.DatetimeIndex(df.index)

Plot:

df.plot()
DYZ
  • 55,249
  • 10
  • 64
  • 93
0

Borrowed liberally from this answer, which you should go out and upvote:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

df = <set_your_data_frame_here>

myDates = pd.to_datetime(df['Month'])
myValues = df['Energy_MWh']
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%b-%Y")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

enter image description here

user1717828
  • 7,122
  • 8
  • 34
  • 59
  • Thanks, this was exactly what I wanted. My current x-axis labels are `Jan 1979, Jan 1983, Jan 1987...`. Is there a way I could show more intervals? For example, instead of an interval of 4 years, I want it to be 2 years. – kev Dec 02 '18 at 23:34
  • 1
    I know next to nothing about matplotlib, but I [searched your question](https://www.google.com/search?q=%22matplotlib%22+%22interval+of+4+years%22&ie=utf-8&oe=utf-8) and found [another one](https://stackoverflow.com/q/24943991/1717828) that seems very similar. The accepted (and only) answer there is code I would copy/paste here, but I'm sure you'll be able to adapt it to your own use case yourself. – user1717828 Dec 03 '18 at 10:27