enter image description here

My code:

import matplotlib.pyplot as plt
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.ylabel('PM2.5 Value')
    plt.title('PM2.5 Time Series')
    return plt.show();

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

1 Answer 1


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)
    # Adjust the x-axis
    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.ylabel('PM2.5 Value')
    plt.title('PM2.5 Time Series')

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

Resulting plot: enter image description here

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.