ricksterrocket
ricksterrocket

Reputation: 79

matplotlib scatter plot with full year date-time index

I have a pandas series with a datetime index and values from the year 2015. Not all dates have data, so dropna() was employed to look at attained data. Part of the data is displayed below, there are roughly 50 dates with observations in the whole series.

  date       value

2015-02-09     8.3
2015-04-17    27.8
2015-05-07    30.6
...
2015-07-27    33.9
2015-07-29    36.1
2015-08-19    32.8
...
2015-12-25    11.1
2015-12-26    11.7

How would I create a matplotlib scatter plot out of this data, using the full year of 2015 as the range of the x-axis?

Upvotes: 1

Views: 956

Answers (1)

Arne
Arne

Reputation: 10545

Pandas has its own plotting method for this, which is a wrapper for the matplotlib function:

import pandas as pd

<name of your series>.plot(xlim=[pd.to_datetime('2015-01-01'), 
                                 pd.to_datetime('2015-12-31')])

This may draw a lineplot by default, which is the conventional way to display time series. But you can use all the usual matplotlib keyword arguments and plotting functions to customize the plot.


Follow-up question: How to overlay several plots with the same x limits?

If the two series you want to plot are the two columns of one DataFrame, you can use the same method as above. Just substitute the DataFrame for the Series.

If the second dataset you want to plot is something else (say (x, y)), you may want to use the more flexible object-oriented matplotlib interface:

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots() 

ax.plot(<series>.index, <series>.values)
ax.plot(x, y)

ax.set_xlim([pd.to_datetime('2015-01-01'), 
             pd.to_datetime('2015-12-31')])

Upvotes: 1

Related Questions