首页 > 解决方案 > 使用 Python 在同一图中绘制两个猫图

问题描述

我正在尝试在同一个图中绘制两个猫图。我尝试使用 subplot() 函数但没有结果。这是我用于一次绘制一个 catplot 的代码。

第一个猫图

fig, axs =plt.subplots(2,1)
sns.catplot(x = 'day',y = 'count',data=day_of_month_count,
            kind ='bar',
            height = 8 , aspect= 1.5,ax=axs[0])

在此处输入图像描述

第二个猫图

这是正在绘制的第二个 catplot :

sns.catplot(x = 'day',y = 'count',data=day_of_month_count,
           kind ='bar',
           height = 8 , aspect= 1.5,ax=axs[1])

在此处输入图像描述

目标在同一图中绘制猫图(一个并排)

我尝试了这样的事情(带有子图),但它不起作用。

fig, axs =plt.subplots(2,1)
sns.catplot(x = 'day',y = 'count',data=day_of_month_count,
            kind ='bar',
            height = 8 , aspect= 1.5,ax=axs[0])
sns.catplot(x = 'month',y = 'count',data=month_of_the_year_count,
           kind ='bar',
           height = 8 , aspect= 1.5,ax=axs[1])

有什么选择吗?解决方案?

标签: pythonmatplotlibseaborn

解决方案


首先,彼此相邻需要 1 行 2 列。然后以下方法按预期正常工作。

在这里,您必须关闭/隐藏catplot. 这可以使用正确的索引和plt.close. 数字的索引/编号从 0 开始。这是一个示例答案。

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
exercise = sns.load_dataset("exercise")

fig, axs = plt.subplots(1,2)

sns.catplot(x="time", y="pulse", kind ='bar', data=exercise, ax=axs[0])
sns.catplot(x="time", y="pulse", kind ='bar', data=exercise, ax=axs[1])
plt.close(2)
plt.close(3)

fig.tight_layout()

在此处输入图像描述


推荐阅读