1

I want the x values to be "yyyy-mm" from 2016-01 to 2020-01 (interval per half year). However, tried many ways the x values still in a mess.
My code is as follows:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

df = pd.read_csv('fcc-forum-pageviews.csv',index_col='date')
df = df[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]

fig = plt.figure()
fig.set_figwidth(15)
fig.set_figheight(9)
ax = fig.add_subplot(1,1,1)
ax.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
ax.set_xlabel('Date')
ax.set_ylabel('Page Views')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.plot(df['value'],color='r')

The following is the result: enter image description here

However, what I expected should be: enter image description here

The dataset can be downloaded from here.Any help is highly appreciated.

After @r-beginners help, I have updated the code as follows:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

df = pd.read_csv('fcc-forum-pageviews.csv',index_col='date')
df = df[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]
df.index = pd.to_datetime(df.index)

fig = plt.figure()
fig.set_figwidth(15)
fig.set_figheight(9)
ax = fig.add_subplot(1,1,1)
ax.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
ax.set_xlabel('Date')
ax.set_ylabel('Page Views')
ax.set_xticks(range(len(df.index)))
ax.set_xticklabels(range(len(df.index)))
months = mdates.MonthLocator(interval=6)
months_fmt = mdates.DateFormatter('%Y-%m')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
ax.plot(df['value'], color='r')

now it can display the x values in 6-month interval. However, instead of starting from 2016-07 (the date from the dataframe), it starts from 1970-02. Any hints? Thanks.

enter image description here

2 Answers 2

2

Convert the date data to pd.to_datetime() You can use MonthLocator to control it. The interval is set to 6 months.

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

df = pd.read_csv('fcc-forum-pageviews.csv',index_col='date')
df = df[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]
df.index = pd.to_datetime(df.index)

fig = plt.figure()
fig.set_figwidth(15)
fig.set_figheight(9)
ax = fig.add_subplot(1,1,1)
ax.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
ax.set_xlabel('Date')
ax.set_ylabel('Page Views')
# ax.set_xticks(range(len(df.index)))
# ax.set_xticklabels(range(len(df.index)))
# months = mdates.MonthLocator(interval=6)
# months_fmt = mdates.DateFormatter('%Y-%m')
# ax.xaxis.set_major_locator(months)
# ax.xaxis.set_major_formatter(months_fmt)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.plot(df['value'], color='r')

enter image description here

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks. I can see the interval is 6 months now. However, the starting yyyy-month was 1970-02 instead of the year-month from the dataframe (should be 2016-07). Do you know why? What is wrong with ax.plot(df.index, df['value'], color='r')? seems the x values was not starting from the date in the dataset
I suspect this may be the cause of the problem, but even after dealing with it, it didn't get it right. Are you also 'matplotlib:3.3.0'?
Yes, the version is 'matplotlib:3.3.0'
The cause was elsewhere. The dates were not in chronological form. Fixed the code.
You can do this simply by converting the next date/time format to pd.to_datetime() in your original code.
|
0

Please read on Xticks

From the docs

>>> locs, labels = xticks()  # Get the current locations and labels.
>>> xticks(np.arange(0, 1, step=0.2))  # Set label locations.
>>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue'])  # Set text labels.
>>> xticks([0, 1, 2], ['January', 'February', 'March'],
...        rotation=20)  # Set text labels and properties.
>>> xticks([])  # Disable xticks.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.