【问题标题】:Changing the formatting of a datetime axis in matplotlib在 matplotlib 中更改日期时间轴的格式
【发布时间】:2017-10-13 14:50:31
【问题描述】:

我有一个索引为datetime 的系列,我想绘制它。我想在 y 轴上绘制系列的值,在 x 轴上绘制系列的索引。 Series 如下所示:

2014-01-01     7
2014-02-01     8
2014-03-01     9
2014-04-01     8
...

我使用plt.plot(series.index, series.values) 生成图表。但是图表看起来像:

问题是我只想有年份和月份(yyyy-mm 或 2016 年 3 月)。但是,该图包含小时、分钟和秒。如何删除它们以获得所需的格式?

【问题讨论】:

    标签: python pandas datetime matplotlib python-datetime


    【解决方案1】:

    你可以试试这样的:

    import matplotlib.dates as mdates
    import matplotlib.pyplot as plt
    df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
    fig,ax1 = plt.subplots()
    plt.plot(df.index,df.values)
    monthyearFmt = mdates.DateFormatter('%Y %B')
    ax1.xaxis.set_major_formatter(monthyearFmt)
    _ = plt.xticks(rotation=90)
    

    【讨论】:

      【解决方案2】:
      import numpy as np
      import pandas as pd
      import matplotlib.pyplot as plt
      import matplotlib.dates as mdates
      
      # sample data
      N = 30
      drange = pd.date_range("2014-01", periods=N, freq="MS")
      np.random.seed(365)  # for a reproducible example of values
      values = {'values':np.random.randint(1,20,size=N)}
      df = pd.DataFrame(values, index=drange)
      
      fig, ax = plt.subplots()
      ax.plot(df.index, df.values)
      ax.set_xticks(df.index)
      
      # use formatters to specify major and minor ticks
      ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
      ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
      _ = plt.xticks(rotation=90)    
      

      【讨论】:

        【解决方案3】:

        你应该看看这个 matplotlib 的原生函数:

        fig.autofmt_xdate()
        

        查看源网站Custom tick formatter上的示例

        【讨论】:

          猜你喜欢
          • 2020-02-02
          • 2020-12-07
          • 2019-12-19
          • 2016-10-19
          • 1970-01-01
          • 2019-06-28
          • 2020-10-30
          相关资源
          最近更新 更多