首页 > 解决方案 > 无法使用 seaborn 绘制双轴

问题描述

当我尝试在 jupyter notebook 中使用 seaborn 绘制双轴图时遇到问题重要说明:该代码在 Python 2 中运行良好。

使用 anaconda 升级到 Python 3 后,我收到了一个愚蠢的错误消息:

/Users/enyi/opt/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py:3720: UserWarning: catplot is a figure-level function and does not accept target axes. You may wish to try countplot
  warnings.warn(msg, UserWarning)

这是我的代码的输出图像:

我的代码的输出

我的代码:

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

df = pd.read_csv('tips.csv')

fig, ax = plt.subplots(1,2,figsize = (10,5))

sns.catplot(x='sex', hue = 'group', data= df, kind = 'count', ax=ax[0])
sns.catplot(x='sex', y='conversion',hue = 'group', data= df, kind = 'bar',ax=ax[2])

plt.show()

标签: pythonmatplotlibseaborn

解决方案


我看不出您的代码如何与 Python2 一起工作,但这无关紧要。错误消息清楚地告诉您catplot不带ax=参数。如果要在子图上绘图,则必须使用底层绘图功能(在第一种情况下,countplot如错误所示)

fig, ax = plt.subplots(1,2,figsize = (10,5))
sns.countplot(x='sex', hue = 'group', data= df, ax=ax[0])
sns.barplot(x='sex', y='conversion',hue = 'group', data= df,ax=ax[1])

推荐阅读