首页 > 解决方案 > 覆盖两个不同大小的 seaborn 条形图

问题描述

假设有两个数据集:一个大的“背景”集和小得多的“前景”集。前景集来自背景,但可能要小得多。

我有兴趣以有序的方式显示整个背景分布sns.barplot,并让前景设置更明亮的对比色以引起对这些样本的注意。

我能找到的最佳解决方案是将一个图表显示在另一个图表之上,但会发生什么情况是图表缩小到较小的域。这就是我的意思:

import matplotlib.pyplot as plt
import seaborn

# Load the example car crash dataset
crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False)

# states of interest
txcahi = crashes[crashes['abbrev'].isin(['TX','CA','HI'])]

# Plot the total crashes
f, ax = plt.subplots(figsize=(10, 5))
plt.xticks(rotation=90, fontsize=10)
sns.barplot(y="total", x="abbrev", data=crashes, label="Total", color="lightgray")

# overlay special states onto gray plot as red bars
sns.barplot(y="total", x="abbrev", data=txcahi, label="Total", color="red")
sns.despine(left=True, bottom=True)

该数据产生: 在此处输入图像描述

但它应该看起来像这样(忽略风格差异): 在此处输入图像描述

为什么这种方法不起作用,什么是更好的方法来实现这一点?

标签: pandasmatplotlibseaborn

解决方案


seaborn只是根据to的值barplot绘制其n数据。相反,如果您使用具有单元意识的 matplotlib 图(从 matplotlib 2.2 开始),它将按预期工作。0n-1bar

import matplotlib.pyplot as plt
import seaborn as sns

# Load the example car crash dataset
crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False)

# states of interest
txcahi = crashes[crashes['abbrev'].isin(['TX','CA','HI'])]

# Plot the total crashes
f, ax = plt.subplots(figsize=(10, 5))
plt.xticks(rotation=90, fontsize=10)

plt.bar(height="total", x="abbrev", data=crashes, label="Total", color="lightgray")
plt.bar(height="total", x="abbrev", data=txcahi, label="Total", color="red")

sns.despine(left=True, bottom=True)

在此处输入图像描述


推荐阅读