Jason
Jason

Reputation: 4546

Using a Pandas dataframe index as values for x-axis in matplotlib plot

I have time series in a Pandas dateframe with a number of columns which I'd like to plot. Is there a way to set the x-axis to always use the index from a dateframe? When I use the .plot() method from Pandas the x-axis is formatted correctly however I when I pass my dates and the column(s) I'd like to plot directly to matplotlib the graph doesn't plot correctly. Thanks in advance.

plt.plot(site2.index.values, site2['Cl'])
plt.show()

output

FYI: site2.index.values produces this (I've cut out the middle part for brevity):

array([
    '1987-07-25T12:30:00.000000000+0200',
    '1987-07-25T16:30:00.000000000+0200',
    '2010-08-13T02:00:00.000000000+0200',
    '2010-08-31T02:00:00.000000000+0200',
    '2010-09-15T02:00:00.000000000+0200'
], 
dtype='datetime64[ns]')

Upvotes: 35

Views: 140843

Answers (5)

Bovett
Bovett

Reputation: 1

You can use

x=yourDataFrame.index.values

which will use the values of the indices of yourDataFrame on the x-axis

Upvotes: 0

Knight
Knight

Reputation: 1

you want to use matplotlib to select a 'sensible' scale just like me, there is one way can solve this question. using a Pandas dataframe index as values for x-axis in matplotlib plot. Code:

ax = plt.plot(site2['Cl'])
x_ticks = ax.get_xticks() # use matplotlib default xticks
x_ticks = list(filter(lambda x: x in range(len(site2)), x_ticks))
ax.set_xticklabels([' '] + site2.index.iloc[x_ticks].to_list())

Upvotes: -1

Anonymous Atom
Anonymous Atom

Reputation: 111

That's Builtin Right Into To plot() method

You can use yourDataFrame.plot(use_index=True) to use the DataFrame Index On X-Axis.

The "use_index=True" sets the DataFrame Index on the X-Axis.

Read More Here: https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.html

Upvotes: 2

Jason
Jason

Reputation: 4546

It seems the issue was that I had .values. Without it (i.e. site2.index) the graph displays correctly.

Upvotes: 13

Higgs
Higgs

Reputation: 622

You can use plt.xticks to set the x-axis

try:

plt.xticks( site2['Cl'], site2.index.values ) # location, labels
plt.plot( site2['Cl'] )
plt.show()

see the documentation for more details: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

Upvotes: 12

Related Questions