【问题标题】:Seaborn hexbin plot with marginal distributions for datetime64[ns] and category variables带有 datetime64[ns] 和类别变量边际分布的 Seaborn hexbin 图
【发布时间】:2021-12-30 20:31:14
【问题描述】:

我正在将电子表格从 excel 上传到数据框。在这张表中,我只对两列感兴趣。第一列是日期和时间,格式为 %Y-%m-%d %H-%M-%S。第二列是分类变量,即违规类型(例如迟到)。 总共有几种违规行为。大约6-7种。 使用命令 df.info () 您可以确保可用列的数据框具有日期和时间列的 datatime64[ns] 类型和 >category 类型用于包含违规类型的列。 我想使用 seaborn 库(https://seaborn.pydata.org/examples/hexbin_marginals.html)中的边际分布的 hexbin 图。但是,上面链接中提供的简单代码对于具有类别和时间的变量来说并不是那么简单。

import seaborn as sns
sns.set_theme(style="ticks")

sns.jointplot(x=df['incident'], y=['date-time'], kind="hex", color="#4CB391")

编译器报告 TypeError: The x variable is categorical, but one of ['numeric', 'datetime'] is required

我了解纵坐标轴需要数字变量或日期时间变量。转换并不能解决问题。

这个错误可以用

重现
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

from datetime import datetime


ndf = pd.DataFrame({'date-time': ['2021-11-15 00:10:00','2021-11-15 00:20:00'], 'incident': ['a','b']})
print(ndf)

sns.set_theme(style="ticks")

sns.jointplot(data=ndf, x='incident', y='date-time', color="#4CB391", hue=ndf['incident'] )

plt.show()

问题。如何得到一个情节看起来像seabron style

【问题讨论】:

  • 这种图对于纯分类数据没有多大意义。如果有一些从类别到数字的“自然”映射,您可以尝试类似df['incident']=df['incident'].map({'a': 1, 'b': 3, 'c':2,...})

标签: pandas seaborn jointplot


【解决方案1】:

根据问题中引用的示例作为所需的图形样式,将x轴上的数据更改为日期/时间数据,将其转换为matplotlib可以处理的日期格式,并将其放置为勾号在 x 轴上。通过将时间序列转换回其原始格式来放置刻度。由于日期和时间重叠,因此文本的角度发生了变化。另外,请自行判断@JohanC 指出的要点。

import numpy as np
import seaborn as sns
sns.set_theme(style="ticks")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

rs = np.random.RandomState(11)
x = rs.gamma(2, size=1000)
date_rnge = pd.date_range('2021-11-15', '2021-11-16', freq='1min')
y = -.5 * x + rs.normal(size=1000)

g = sns.jointplot(x=mdates.date2num(date_rng[:1000]), y=y, kind="hex", color="#4CB391")
g.ax_joint.set_xticklabels([mdates.num2date(d).strftime('%Y-%m-%d %H:%M:%S') for d in mdates.date2num(date_rng[:1000])])

for tick in g.ax_joint.get_xticklabels():
    tick.set_rotation(45)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 2020-01-16
    • 1970-01-01
    • 2023-03-03
    • 2016-11-26
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    相关资源
    最近更新 更多