Home > Mobile >  Plot the 2 graphs with same y scale
Plot the 2 graphs with same y scale

Time:05-08

I need to draw 2 bar graphs with the same x axis. It was done as shown below. Buy their heights are not comparable, since the y axis have been drawn with le8 in the left hand side and le9 with the right hand side. Cannot I bring them to the same scale? for an example loth are into le8? Following is the code I used.

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()

enter image description here

CodePudding user response:

  • ax.set_ylim() sets the y limits of ax
  • ax2.get_ylim() gets the current y limits of ax2

With this in mind, you can just write:

ax.set_ylim(ax2.get_ylim())

Thins will make the data in ax look way smaller since it's a order of magnitude less.

CodePudding user response:

In your case, you want to display the same type of value (sale values) of objects but from different sources. I strongly recommend you should rather use the hue' keyword in seaborn` than try to modify the figure manually. Firstly, make your dataframe somewhat like this:

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

Then you can easily create a barplot as expected:

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