【问题标题】:Seaborn plot with shared x axis具有共享 x 轴的 Seaborn 图
【发布时间】:2020-03-06 05:35:21
【问题描述】:

我正在尝试绘制数据框的 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')

【问题讨论】:

  • 这能回答你的问题吗? How can I overlay two graphs in Seaborn?
  • 不。这正是我在我的代码中所做的并且不起作用。
  • A scatterplot 是数字图,条形图是 categorical 图,因此几乎不可能将它们放在同一个图上。 Matplotlib 的 barscatter 都是数字的,所以可以正常工作。

标签: python matplotlib seaborn


【解决方案1】:

您可以使用x=np.arange(0,len(df)) 而不是x="Announced Year"scatterplot 绘制共享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')

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 2019-02-03
    • 2019-09-03
    • 1970-01-01
    • 2019-03-22
    • 2021-07-05
    • 2020-06-11
    • 2021-08-01
    • 2018-11-07
    相关资源
    最近更新 更多