Matplotlib/Seaborn直方图中的轴刻度标记

3
我有一个包含WhatsApp聊天消息、发送者和对应日期时间格式的数据框df。
时间 发送者 消息 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轴上的刻度不太合理,虽然应该是24个,但最终却有30个,而且所有刻度都包含整个日期和时间,我只想要"%H:%M"格式的时间。
错误的刻度从哪里来?
谢谢!
1个回答

5

Seaborn和Pandas都使用Matplotlib进行绘图。让我们看看谁返回bin值,我们需要调整x轴刻度:

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

示例输出: ![enter image description here

从这个练习中可以得出结论,所有三个引用指向相同的例程。因此,我们可以直接使用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中可能有更简单的方法,但我不知道。如果这些库有任何更好的建议,我很乐意点赞。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接