【问题标题】:Axis ticks in histogram of times in matplotlib/seabornmatplotlib/seaborn 中时间直方图中的轴刻度
【发布时间】:2021-03-31 03:13:25
【问题描述】:

我有一个 df,其中包含来自 WhatsApp 聊天的消息、发件人以及日期时间格式的相应时间。

Time Sender Message
2020-12-21 22:23:00 Sender 1 "..."
2020-12-21 22:26:00 Sender 2 "..."
2020-12-21 22:35:00 Sender 1 "..."

我可以用sns.histplot(df["Time"], bins=48)绘制直方图

但是现在 x 轴上的刻度没有多大意义了。我最终得到 30 个刻度,即使它应该是 24,而且刻度都包含整个日期加上我只想要 "%H:%M" 中的时间的时间

错误刻度的问题出在哪里?

谢谢!

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    seaborn 和 pandas 都使用 matplotlib 来绘制函数。让我们看看谁返回 bin 值,我们需要调整 x-ticks:

    import numpy as np
    import pandas as pd
    import seaborn as sns
    from matplotlib import pyplot as plt
    
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
    
    #fake data generation
    np.random.seed(1234)
    n=20
    start = pd.to_datetime("2020-11-15")
    df = pd.DataFrame({"Time": pd.to_timedelta(np.random.rand(n), unit="D") + start, "A": np.random.randint(1, 100, n)})
    #print(df)
    
    #pandas histogram plotting function, left
    pd_g = df["Time"].hist(bins=5, xrot=90, ax=ax1)
    #no bin information
    print(pd_g)
    ax1.set_title("Pandas")
    
    #seaborn histogram plotting, middle
    sns_g = sns.histplot(df["Time"], bins=5, ax=ax2)
    ax2.tick_params(axis="x", labelrotation=90)
    #no bin information
    print(sns_g)
    ax2.set_title("Seaborn")
    
    #matplotlib histogram, right
    mpl_g = ax3.hist(df["Time"], bins=5, edgecolor="white")
    ax3.tick_params(axis="x", labelrotation=90)
    #hooray, bin information, alas in floats representing dates
    print(mpl_g)
    ax3.set_title("Matplotlib")
    
    
    plt.tight_layout()
    plt.show()
    

    示例输出:

    从这个练习中,我们可以得出结论,所有三个都指的是同一个例程。因此,我们可以直接使用 matplotlib,它为我们提供 bin 值:

    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt
    from matplotlib.dates import num2date
    
    fig, ax = plt.subplots(figsize=(8, 5))
    
    #fake data generation
    np.random.seed(1234)
    n=20
    start = pd.to_datetime("2020-11-15")
    df = pd.DataFrame({"Time": pd.to_timedelta(np.random.rand(n), unit="D") + start, "A": np.random.randint(1, 100, n)})
    
    #plots histogram, returns counts, bin border values, and the bars themselves
    h_vals, h_bins, h_bars = ax.hist(df["Time"], bins=5, edgecolor="white")
    
    #plot x ticks at the place where the bin borders are
    ax.set_xticks(h_bins)
    #label them with dates in HH:MM format after conversion of the float values that matplotlib uses internally
    ax.set_xticklabels([num2date(curr_bin).strftime("%H:%M") for curr_bin in h_bins])
    
    plt.show()
    

    示例输出:

    Seaborn 和 pandas 让生活更轻松,因为它们为常用的绘图功能提供了方便的包装器和一些附加功能。但是,如果它们提供的参数不够,人们通常不得不恢复到 matplotlib,它可以做的事情更灵活。显然,我不知道在 pandas 或 seaborn 中可能有更简单的方法。我很乐意在这些库中支持任何更好的建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 2021-04-03
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多