代码之家  ›  专栏  ›  技术社区  ›  adhg veen

线条图不显示轴中的所有日期

  •  0
  • adhg veen  · 技术社区  · 6 年前

    我有以下几点:

    fig, ax = plt.subplots(figsize=(40, 10))
    sns.lineplot(x="Date", y="KFQ imports", data=df_dry, color="BLACK", ax=ax)
    sns.lineplot(x="Date", y="QRR imports", data=df_dry, color="RED",ax=ax)
    
    ax.set(xlabel="Date", ylabel="Value", )
    x_dates = df_dry['Date'].dt.strftime('%b-%Y')
    ax.set_xticklabels(labels=x_dates, rotation=45)
    

    结果 enter image description here

    当我使用条形图时( sns.barplot )显示了整个日期范围。我是不是漏掉了点什么?我

    1 回复  |  直到 6 年前
        1
  •  2
  •   ImportanceOfBeingErnest    6 年前

    我们的想法是将xticks精确设置为数据框中的日期。为此,你可以使用 set_xticks(df.Date.values) . 然后,可以为日期使用自定义格式设置工具,这样可以按照您想要的方式对日期进行格式设置。

    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import dates
    import seaborn as sns
    
    df = pd.DataFrame({"Date" : ["2018-01-22", "2018-04-04", "2018-12-06"],
                       "val"  : [1,2,3]})
    df.Date = pd.to_datetime(df.Date)
    
    
    ax = sns.lineplot(data=df, x="Date", y="val", marker="o")
    ax.set(xticks=df.Date.values)
    ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b-%Y"))
    plt.show()
    

    enter image description here

    请注意,在没有Seaborn的情况下,如何实现这一点,

    ax = df.set_index("Date").plot(x_compat=True, marker="o")
    ax.set(xticks=df.Date.values)
    ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b-%Y"))
    plt.show()