python - 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" 中的时间的时间
错误刻度的问题出在哪里?
谢谢!
解决方案
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 中可能有更简单的方法。我很乐意在这些库中提出任何更好的建议。
推荐阅读
- ruby-on-rails - CSS Loader Invalid Options 选项不应在 validateOptions 与 react_rails 应用程序中具有其他属性
- python - 如何在表格的 3 列中的 2 列中将度数转换为弧度?
- bash - Bash 脚本从命令行运行,但不能使用 Launchd
- javascript - 捆绑失败:错误:无法解析模块`react-native/Libraries/StyleSheet/ColorPropType.js`
- amazon-cloudwatch - 如何自动化 Cloud Watch 仪表板。?
- python - 熊猫如何计算列值加起来达到阈值的行数
- wpf - 如何让 Add_PreviewMouseDown 与 2 个窗口和 .Show() 一起工作?
- java - MQ : 已达到通道实例的最大数量
- json - 如何反序列化 Xamarin Forms 中的多个对象?
- sql-server - 提高 SQL 查询效率