绘制具有相同 y 刻度的 2 个图

Plot the 2 graphs with same y scale

我需要绘制 2 个具有相同 x 轴的条形图。如下图所示。 Buy 它们的高度不可比,因为 y 轴的左侧为 le8,右侧为 le9。我不能把它们带到同样的规模吗?例如,很多人都喜欢 le8?以下是我使用的代码。

def extract_top_20_movie_details(dataframe):
    top_20_domestic_movies = dataframe.nlargest(10,'Domestic Sales (in $)')
    top_20_international_movies = dataframe.nlargest(10,'International Sales (in $)')
    
    plt.figure(figsize=(13,7))
    # who v/s fare barplot
    ax=sns.barplot(x = 'Title',
                y = 'Domestic Sales (in $)',
                data = top_20_domestic_movies)
    plt.xticks(rotation=75)
    
    width_scale = 0.45
    for bar in ax.containers[0]:
        bar.set_width(bar.get_width() * width_scale)

    ax2 = ax.twinx()
    sns.barplot(y = 'International Sales (in $)', x = 'Title', data=top_20_domestic_movies, alpha=0.7, hatch='xx')
    for bar in ax2.containers[0]:
        x = bar.get_x()
        w = bar.get_width()
        bar.set_x(x + w * (1- width_scale))
        bar.set_width(w * width_scale)

    plt.ticklabel_format(useOffset=False)

    # Show the plot
    plt.show()

  • ax.set_ylim() 设置 ax
  • 的 y 限制
  • ax2.get_ylim() 获取 ax2
  • 的当前 y 限制

考虑到这一点,您可以这样写:

ax.set_ylim(ax2.get_ylim())

Thins 会使 ax 中的数据看起来小得多,因为它的数量级少了。

在您的情况下,您想要显示相同类型的对象的价值(销售价值)但来自不同的来源。我强烈建议您宁愿使用 hue' keyword in seaborn` 而不是尝试手动修改图形。 首先,让你的数据框有点像这样:

Movie | Sales | Market|
A     | 100   | Domestic|
A     | 1000  | International|
B     | 40   | Domestic|
B     | 5000  | International|

然后您可以轻松地按预期创建条形图:

sns.barplot(x="Movie",y="Sales", hue="Market", data=df)
``