How do I print full date in the x axis of the line plot here?

My code:

import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams["figure.figsize"] = [12,6]
def time_series(start, end):
time_series_df = df[['Date', 'Value']][(df['Date'] >= start) & (df['Date'] <= end)]
x = time_series_df.Date
y = time_series_df.Value
plt.plot(x,y)
plt.xlabel('Time')
plt.ylabel('PM2.5 Value')
plt.title('PM2.5 Time Series')
return plt.show();

time_series('2014','2019')

• What exactly are you after? Changing e.g. '2014' to '2014-01-01'? Feb 4 '21 at 5:40
• yes. and more frequent dates rather than just one date from every year.
– ash
Feb 4 '21 at 5:45
• How frequent? If there are too many labels then you will have a problem of them significantly overlapping. Feb 4 '21 at 6:16
• yes.maybe one date per month
– ash
Feb 4 '21 at 7:19

For better control over the x-axis formatting, you can use the matplotlib.dates methods. In your case, MonthLocator and DateFormatter could be of interest. These can be used to adjust the x-axis as follows:

import matplotlib.dates as mdates

def time_series(start, end):
time_series_df  = df.loc[(df['Date'] >= start) & (df['Date'] <= end), ['Date', 'Value']]
time_series_df = time_series_df.set_index('Date')

fig, ax = plt.subplots(1)
ax.plot(time_series_df)

ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3)) # Month intervals
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # date formatting
# automaticall set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

plt.xlabel('Time')
plt.ylabel('PM2.5 Value')
plt.title('PM2.5 Time Series')
plt.show()


Note the interval=3 argument for MonthLocator. This is the frequency of the x-axis ticks.

Resulting plot:

Dataframe use for the plot above:

df = pd.DataFrame({'Date': pd.date_range(start='2014-01-01', end='2018-12-31'), 'Value': np.random.uniform(size=1826)})
df['Date'] = pd.to_datetime(df['Date'])