【问题标题】:matplotlib.pyplot x values not displayed as expectedmatplotlib.pyplot x 值未按预期显示
【发布时间】:2020-08-05 04:29:43
【问题描述】:

我希望从 2016-01 到 2020-01(每半年的间隔)的 x 值是“yyyy-mm”。但是,尝试了很多方法,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')

结果如下:

但是,我的预期应该是:

数据集可以从here下载。非常感谢任何帮助。

经过@r-beginners的帮助,我更新了代码如下:

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

现在它可以以 6 个月的间隔显示 x 值。但是,它不是从 2016-07(数据框的日期)开始,而是从 1970-02 开始。有什么提示吗?谢谢。

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案1】:

    将日期数据转换为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')
    

    【讨论】:

    • 谢谢。我现在可以看到间隔是6个月。但是,开始的 yyyy 月是 1970-02,而不是数据框中的年月(应该是 2016-07)。你知道为什么吗? ax.plot(df.index, df['value'], color='r') 有什么问题?似乎 x 值不是从数据集中的日期开始
    • 我怀疑this 可能是问题的原因,但即使在处理之后,它也没有正确处理。你也是'matplotlib:3.3.0'吗?
    • 是的,版本是'matplotlib:3.3.0'
    • 原因在别处。日期不是按时间顺序排列的。修复了代码。
    • 您只需将原始代码中的下一个日期/时间格式转换为pd.to_datetime()即可。
    【解决方案2】:

    请继续阅读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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      相关资源
      最近更新 更多