python - 具有共享 x 轴的 Seaborn 图

标签 python matplotlib seaborn

我正在尝试绘制数据帧的 2 列(一列作为条形图,另一列作为散点图)。我可以使用 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", data=df, ax=ax1)

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

plt.title('2016 to 2019 Announcements')

This is the image I get, where I can't see the scatterplot

最佳答案

您可以使用 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", data=df, ax=ax1)

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

plt.title('2016 to 2019 Announcements')

enter image description here

关于python - 具有共享 x 轴的 Seaborn 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58785983/

相关文章:

python - 如何在seaborn lineplot上显示置信区间(误差带)

python - 解析 xml 查找具有匹配属性的最后一个元素

python - GAE 上有 DAL/ORM 吗?

python - matplotlib:我可以使用辅助字体来丢失字形吗?

python - Seaborn 热图 : y axis ticks and annot

python - 为条形图中的每个条形设置恒定宽度

python - SQLAlchemy 中的依赖 CTE? (里面的例子)

python - 断言包含特定长度字符串的列表

Python 多处理在绘图期间挂起

python - 如何仅绘制seaborn 热图的下三角?