具有共享x轴的Seaborn图

我正在尝试绘制数据帧的两列(一列为条形图,另一列为散点图)。我可以在Matplotlib上使用它,但是我想在Seaborn中使用它。

这是代码:

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

df = pd.DataFrame({'Announced Year': [2016,2017,2018,2019],'Amount Awarded': [12978216,11582629,11178338,11369267],'Number of Awarded': [18,14,13,13]})

fig,ax1 = plt.subplots()

ax2 = ax1.twinx()

sns.scatterplot(x="Announced Year",y="Number of Awarded",data=df,ax=ax2)
sns.barplot(x="Announced Year",y="Amount Awarded",ax=ax1)

fig.tight_layout()  # otherwise the right y-label is slightly clipped

plt.title('2016 to 2019 Announcements')

具有共享x轴的Seaborn图

qingwa406 回答:具有共享x轴的Seaborn图

对于散布图,您可以使用x=np.arange(0,len(df))而不是x="Announced Year"使用共享x轴进行绘制。

fig,ax1 = plt.subplots()

ax2 = ax1.twinx()

sns.barplot(x="Announced Year",y="Amount Awarded",data=df,ax=ax2,alpha=.5)
sns.scatterplot(x=np.arange(0,len(df)),y="Number of Awarded",ax=ax1)

fig.tight_layout()  # otherwise the right y-label is slightly clipped

plt.title('2016 to 2019 Announcements')

enter image description here

本文链接:https://www.f2er.com/3130330.html

大家都在问