Basj
Basj

Reputation: 46303

Plot a Series or Dataframe with pandas, with a longer x-axis than actual data available

I have data until today:

y = pd.Series(np.random.random(23), index=pd.date_range(start='2020-03-01', end='2020-03-23'))

but I'd like to plot it with an x-axis that goes until April 1st (with no points on the graph for 24th to 31st):

x = pd.date_range(start='2020-03-01', end='2020-04-01')

This does not work:

plt.plot(x, y, 'o')
plt.show()

ValueError: x and y must have same first dimension, but have shapes (32,) and (23,)

How can I make the x-axis go beyond available data?

Upvotes: 0

Views: 275

Answers (1)

Nicolas Gervais
Nicolas Gervais

Reputation: 36684

Just add plt.xticks():

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

x = pd.date_range(start='2020-03-01', end='2020-04-01')
y = pd.Series(np.random.random(23), index=pd.date_range(start='2020-03-01',
    end='2020-03-23'))

plt.plot(y)
plt.xticks(x, rotation=35)
plt.show()

enter image description here

Upvotes: 1

Related Questions