35

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]')
0

5 Answers 5

13

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

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

Comments

12

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

1 Comment

Thanks for your response. Is there some way to use matplotlib to select a 'sensible' scale? For instance with the Pandas .plot method it will select days, months or years for the x-axis as appropriate. If I understand the documentation correctly it seems that for every data point of site2['Cl'] there'll be an xtick which will be far too many for my data set. Also I think that something might be wrong with my date because my new graph looks like this
2

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

Comments

0

You can use

x=yourDataFrame.index.values

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

Comments

-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())

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.