matplotlib.pyplot значения x не отображаются должным образом - PullRequest
1 голос
/ 05 августа 2020

Я хочу, чтобы значения x были «гггг-мм» с 2016-01 по 2020-01 (интервал в полгода). Однако пробовал разными способами, значения x все еще в беспорядке. Мой код выглядит следующим образом:

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

Результат: enter image description here

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

The dataset can be downloaded from здесь . Любая помощь приветствуется.

После @ r-beginners help, я обновил код следующим образом:

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

теперь он может отображать значения x с 6-месячным интервалом. Однако вместо того, чтобы начинаться с 2016-07 (дата из фрейма данных), он начинается с 1970-02. Есть подсказки? Спасибо.

введите описание изображения здесь

Ответы [ 2 ]

2 голосов
/ 05 августа 2020

Преобразование данных даты в pd.to_datetime() Вы можете использовать MonthLocator для управления этим. Интервал установлен в 6 месяцев.

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

введите описание изображения здесь

0 голосов
/ 05 августа 2020

Пожалуйста, прочтите Xticks

Из документов

>>> 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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...