日期没有以所需的格式显示在折线图中

时间:2020-07-16 20:02:16

标签: python pandas matplotlib

我有一个plot_graph()函数,可将熊猫数据帧绘制为折线图。

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

我以这种格式传递熊猫数据框

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

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

2 个答案:

答案 0 :(得分:1)

尝试一下:

List<User> usersModified = users.stream().filter(e-> e.getAge()>25).collect(Collectors.toList());
usersModified.forEach(e-> modify(e));

enter image description here

我认为使用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需要将日期设置为 date 日期时间(或字符串)。如果您直接通过df.plot()进行绘制,则不需要这样做。 More here

答案 1 :(得分:1)

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)

enter image description here