【问题标题】:Date does not get displayed in the desired format in line chart日期未在折线图中以所需格式显示
【发布时间】:2020-07-16 20:02:16
【问题描述】:

我有一个 plot_graph() 函数,可以将 pandas 数据框绘制为折线图。

def plot_graph(df):
 ax = plt.gca()
 #df["Date"].dt.strftime("%m/%d/%y")
 #df["date"] = df["date"].astype('datetime64[ns]')
 print(df['date'])
 df.plot(kind='line', x='date', y='Actual', ax=ax)
 df.plot(kind='line', x='date', y='Expected', color='red', ax=ax)
 ax.xaxis.set_major_locator(plt.MaxNLocator(3))
 plt.savefig("fig1.png")

我以这种格式传递 pandas 数据帧

 date       actual   expected
 2019-11    20       65
 2019-12    35       65

当我绘制折线图时,x 轴标签无法以 (yyyy-mm) 格式正确显示。我相信它是日期格式。所以我尝试将其转换为日期。我尝试了所有选项(在代码中注释),似乎没有任何效果。任何建议都会受到欢迎。

【问题讨论】:

  • 使用 Matplotlib 的 DateFormatter?
  • @QuangHoang:效果也不好
  • 你的ax.xaxis.set_major_locator(plt.MaxNLocator(3)) 看起来很危险:-)。
  • @QuangHoang:好的,这是我的尝试之一,但效果不佳

标签: python pandas matplotlib


【解决方案1】:

试试这个:

import pandas as pd
import matplotlib.dates as mdates

def plot_graph(df):
    ax = plt.gca()
    df['date'] = pd.to_datetime(df['date']).dt.date
    df.plot(kind='line', x='date', y='actual', ax=ax)
    df.plot(kind='line', x='date', y='expected', color='red', ax=ax)
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) #to explicitly set format
    
plot_graph(df)

我认为在这里使用 matplotlib.dates 是最好的选择,似乎 df.plot() 需要日期为 date不是 datetime (或字符串)。如果您直接通过matplotlib 进行绘图,则不需要这样做。 More here.

【讨论】:

    【解决方案2】:
    import pandas as pd
    import numpy as np  # for test data
    from datetime import datetime  # for test data
    import matplotlib.dates as mdates
    import matplotlib.pyplot as plt
    
    # synthetic data with date as a datetime
    np.random.seed(365)
    length = 700
    df = pd.DataFrame(np.random.rand(length, 2) * 10, columns=['Actual', 'Expected'], index=pd.bdate_range(datetime.today(), freq='d', periods=length).tolist()).reset_index()
    
    # display(df.head())
           index    Actual  Expected
    0 2020-07-16  9.414557  6.416027
    1 2020-07-17  6.846105  5.885621
    2 2020-07-18  5.438872  3.680709
    3 2020-07-19  7.666258  3.050124
    4 2020-07-20  4.420860  1.104433
    
    
    # function
    def plot_graph(df):
        
        #  df.date = pd.to_datetime(df.date)  # if needed and date is the column name
    
        fig, ax = plt.subplots()
        
        months = mdates.MonthLocator()  # every month
        months_fmt = mdates.DateFormatter('%Y-%m')   # format
    
        ax.plot('index', 'Actual', data=df)
        ax.plot('index', 'Expected', data=df, color='red')
    
        # format the ticks
        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_major_formatter(months_fmt)
        
        plt.xticks(rotation=90)
        
        plt.legend()
    
        plt.show()
    
    
    plot_graph(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      相关资源
      最近更新 更多