首页 > 解决方案 > 组合 Seaborn 地块没有正确排列

问题描述

我正在尝试在 seaborn 的计数图上方叠加一个线图。它们在分开时都可以工作: 在此处输入图像描述

通过放在一起,它们最终位于图表的两端: 在此处输入图像描述

有人知道这是为什么吗?

标签: pythonseaborn

解决方案


您需要使用 matplotlib 中的 twinx() 并且您的第一个图需要只是 matplotlib,而不是 seaborn。我不确定为什么 seaborn 对组合图有问题,但我遇到了和你一样的问题。这是我的代码,其中包含来自 kaggle 的人口数据:

#Create bar plot for annual growth by year
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

#import dataframe for data
df = pd.read_csv('df.csv')

#Create combo chart
fig, ax1 = plt.subplots(figsize=(10,6))
color = 'tab:green'

#bar plot creation
ax1.bar(df['Year'],df['Population Growth'],color='y')

#specify we want to share the same x-axis
ax2 = ax1.twinx()

#lineplot creation
ax2 = sns.lineplot(x='Year', y='Percent Growth', data=df,color='#C33E3E')


plt.show()

使用此代码,我得到以下图表:

带有条形图和折线图的组合图


推荐阅读