【问题标题】:Modifying x ticks labels in seaborn在 seaborn 中修改 x 刻度标签
【发布时间】:2020-10-09 21:06:25
【问题描述】:

我正在尝试将 x-tick 标签的格式修改为日期格式 (%m-%d)。

我的数据包含特定日期期间的每小时数据值。我正在尝试绘制 14 天的数据。但是,当我跑步时,我得到 x 个标签完全混乱。

有什么方法可以只显示日期并跳过 x 轴上的每小时值。 ?有没有办法修改 x 刻度,我可以跳过几个小时的标签并只显示日期的标签?我正在使用 seaborn。

根据评论的建议,我编辑了我的代码以绘制如下:

fig, ax = plt.pyplot.subplots()
g = sns.barplot(data=data_n,x='datetime',y='hourly_return')
g.xaxis.set_major_formatter(plt.dates.DateFormatter("%d-%b"))

但我收到以下错误:

ValueError: DateFormatter found a value of x=0, which is an illegal 
date; this usually occurs because you have not informed the axis that 
it is plotting dates, e.g., with ax.xaxis_date()

检查日期时间列后,我得到以下输出,该列的数据类型类型为:

0     2020-01-01 00:00:00
1     2020-01-01 01:00:00
2     2020-01-01 02:00:00
3     2020-01-01 03:00:00
4     2020-01-01 04:00:00
          ...        
307   2020-01-13 19:00:00
308   2020-01-13 20:00:00
309   2020-01-13 21:00:00
310   2020-01-13 22:00:00
311   2020-01-13 23:00:00
Name: datetime, Length: 312, dtype: datetime64[ns]

我怀疑 x 刻度,所以当我运行 g.get_xticks() [获取 x 轴上的刻度] 时,我得到了序数形式的输出。谁能说出为什么会这样?

【问题讨论】:

    标签: python data-visualization seaborn


    【解决方案1】:

    1。用x轴日期时间绘制线图的方法

    您可以尝试如下更改 x 轴格式

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    from matplotlib import dates
    
    ## create dummy dataframe
    datelist = pd.date_range(start='2020-01-01 00:00:00', periods=312,freq='1H').tolist()
    #create dummy dataframe
    df = pd.DataFrame(datelist, columns=["datetime"])
    df["val"] = [i for i in range(1,312+1)]
    df.head()
    

    下面是数据框信息

    画图

    fig, ax = plt.subplots()
    chart = sns.lineplot(data=df, ax=ax, x="datetime",y="val")
    ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b"))
    

    输出:

    2。使用 seaborn 和 x 轴日期时间绘制条形图的方法

    如果你为barplot绘制,上述方法会出现问题。所以,将使用下面的代码

    fig, ax = plt.subplots()
    ## barplot
    chart = sns.barplot(data=df, ax=ax,x="datetime",y="val")
    
    ## freq of showing dates, since frequency of datetime in our data is 1H. 
    ## so, will have every day 24data points
    ## Trying to calculate the frequency by each day 
    ## (assumed points are collected every hours in each day, 24)
    ## set the frequency for labelling the xaxis
    freq = int(24)
    # set the xlabels as the datetime data for the given labelling frequency,
    # also use only the date for the label
    ax.set_xticklabels(df.iloc[::freq]["datetime"].dt.strftime("%d-%b-%y"))
    # set the xticks at the same frequency as the xlabels
    xtix = ax.get_xticks()
    ax.set_xticks(xtix[::freq])
    # nicer label format for dates
    fig.autofmt_xdate()
    
    plt.show()
    

    输出:

    【讨论】:

    • 执行该命令时出现以下错误:'DateFormatter 发现 x=0 的值,这是非法日期;这通常是因为您没有通知轴它正在绘制日期,例如,使用 ax.xaxis_date()'
    • 表示 x 值不在 datetime 对象中。您将 x 列转换为日期时间对象pd.to_datetime(df["xaxis"])
    • @NaveenGabriel 如果您没有隐式传递 x 轴,那么您可以将数据帧索引值更改为 datetime object
    • 我的数据框列绝对是日期时间对象类型。
    • 你能在这里提供你的 X 轴值吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2020-08-05
    • 2012-06-29
    相关资源
    最近更新 更多