在 Seaborn 中绘制分类数据

问题描述

我已经对数据进行了分类。在特定日期,我有每 15 分钟计算一次的数据(A 到 E)。 当我想用 seaborn 绘图时,我得到了这个:

enter image description here

较大的气泡覆盖较小的气泡,整个内容不易阅读(例如 2020-05-12 在 21:15)。是否可以将每个 15 分钟课程的气泡并排显示,并有一点重叠?

我的代码

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import os

df = pd.read_csv("test_df.csv")
#print(df)



sns.set_theme()

sns.scatterplot(
  data = df,x = "date",y = "time",hue = "category",size = "amount",sizes=(15,200)
)


plt.gca().invert_yaxis()


plt.show()

我的 CSV 文件

date,time,amount,category
2020-05-12,21:15,13,A
2020-05-12,2,B
2020-05-12,5,C
2020-05-12,1,D
2020-05-12,21:30,4,21:45,3,22:15,9,E
2020-05-12,00:15,21,00:30,11,04:15,7,04:30,04:45,A
2020-05-14,C
2020-05-14,D
2020-05-14,B
2020-05-14,E
2020-05-14,05:00,A

解决方法

您可以为此使用seaborn swarmplot。您首先必须使用 .reindex.repeat 将“金额”列分成单独的条目。然后你就可以绘图了。

代码如下:

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import os

df = pd.read_csv("test.csv")

df = df.reindex(df.index.repeat(df.amount))

sns.swarmplot(data = df,x = "date",y = "time",hue = "category")

plt.gca().invert_yaxis()

plt.show()

这是输出: enter image description here