使用 Seaborn 制作水平条形图并使用数字独立数据

3
这是Seaborn如何制作水平箱线图的文档。您会注意到他们使用了一个名为crashes的数据集,并绘制了一些分类变量与一些数值变量之间的图形。要使它水平,他们只需翻转x和y变量即可,非常简单。
我的问题是我的类别是数字,这会导致问题。最小可重现示例使用了他们的数据集。基本上这应该是相同的图形,一个水平,一个垂直。正如您所看到的,它们都是垂直的...
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")


crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False)

crashes['roundTotal'] = np.round(crashes['total']).astype(int)
crashesMod = crashes.groupby(['roundTotal']).count().reset_index()
crashesMod['VsAverage'] = crashesMod['total'] > crashesMod.total.mean()

sns.barplot(x = 'roundTotal', y = 'total', hue = 'VsAverage', data = crashesMod)
plt.show()
sns.barplot(y = 'roundTotal', x = 'total', hue = 'VsAverage', data = crashesMod)

enter image description here

我尝试将类型为字符串的列'roundTotal'创建,因为我想象它在幕后进行了一些猜测,并且在使用2种数值类型时失败了,但是然后我遇到了TypeError: unsupported operand type(s) for /: 'str' and 'int'


1
使用pandas将其转换为分类变量:https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html - Paul H
1
orient="h" - mwaskom
在这里,您可能还希望使用 dodge=False 参数。 - mwaskom
2个回答

3

根据seaborn文档,您应该使用“orient”选项:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

fig, ax = plt.subplots(figsize=(3.5, 6))

crashes = (
    sns.load_dataset("car_crashes")
        .sort_values("total", ascending=False)
        .assign(roundTotal=lambda df: df['total'].round().astype(int).astype('category'))
        .groupby(['roundTotal']).count()
        .reset_index()
        .assign(VsAverage=lambda df: df['total'] > df['total'].mean())
        .pipe((sns.barplot, 'data'), y='roundTotal', x='total',
              hue='VsAverage', orient='horizonal', ax=ax)
)

ax.invert_yaxis()

这给了我:

输入图片说明


3

在绘图之前,只需添加以下内容:

crashesMod.roundTotal=crashesMod.roundTotal.astype('category')
crashesMod.VsAverage=crashesMod.VsAverage.astype('category')

2
最好使用数据框的assign方法,而不是依赖于列的点访问器。 - Paul H
2
@qwertylpc 使用.assign创建一个全新的列以进行绘图。你甚至可以将该结果直接传输到seaborn中,使其完全短暂。 - Paul H
@PaulH 你知道如何控制列的顺序吗?例如,在示例中,y轴从6到24(降序)而不是升序。我刚刚尝试了调用sort_values() - qwertylpc
1
@qwertylpc,请看下面我的回答。 - Paul H

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