0
$\begingroup$

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

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)
    
    # 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.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: 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'])
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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