首页 > 解决方案 > matplotlib/seaborn 中时间直方图中的轴刻度

问题描述

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

时间 发件人 信息
2020-12-21 22:23:00 发件人 1 “……”
2020-12-21 22:26:00 发件人 2 “……”
2020-12-21 22:35:00 发件人 1 “……”

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

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

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

谢谢!

标签: pythonmatplotlibseaborn

解决方案


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 中可能有更简单的方法。我很乐意在这些库中提出任何更好的建议。


推荐阅读