Search code examples
pythonseabornbar-chart

How to plot two y-axis barplot using seaborn


I need to plot a bar chart using seaborn with two y-axis (y1 column on the left y-axis and y2 column on the right y-axis) but I have no idea how to make it. Please see the following written code the plot only one y-axis (see the picture). I would be grateful if somebody help me.

enter image description here

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

GWWs_eff_df = pd.DataFrame({'BMP': ['CC', 'CC','CC', 'CC','GWWs','GWWs','GWWs','GWWs'], 'y1': [97,78,31,21,34,40,33,60],'y2': [100,85,85,94,45,67,89,90],'Season': ['Spring (Mar-Apr-May)', 'Summer (Jun-Jul-Aug)', 'Fall (Sep-Oct-Nov)', 'Winter (Dec-Jan-Feb)','Spring (Mar-Apr-May)', 'Summer (Jun-Jul-Aug)', 'Fall (Sep-Oct-Nov)', 'Winter (Dec-Jan-Feb)']})

import seaborn as sns
sns.set_style('whitegrid')
g = sns.catplot(
    data=GWWs_eff_df, x="BMP", y="y1", col="Season",
    kind="bar", height=4, aspect=.6,
)
for ax in g.axes.flat[1:]:
    sns.despine(ax=ax, left=True)
for ax in g.axes.flat:
    ax.set_xlabel(ax.get_title())
    ax.set_title('')
    ax.margins(x=0.1) # slightly more margin as a separation
plt.subplots_adjust(wspace=0, bottom=0.18, left=0.06)
plt.show()

Solution

  • enter image description here

    First create a figure with two subplots (1 row, 2 columns) and sets the overall figure:

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    GWWs_eff_df = pd.DataFrame({
        'BMP': ['CC', 'CC', 'CC', 'CC', 'GWWs', 'GWWs', 'GWWs', 'GWWs'],
        'y1': [97, 78, 31, 21, 34, 40, 33, 60],
        'y2': [100, 85, 85, 94, 45, 67, 89, 90],
        'Season': ['Spring (Mar-Apr-May)', 'Summer (Jun-Jul-Aug)', 'Fall (Sep-Oct-Nov)', 'Winter (Dec-Jan-Feb)',
                   'Spring (Mar-Apr-May)', 'Summer (Jun-Jul-Aug)', 'Fall (Sep-Oct-Nov)', 'Winter (Dec-Jan-Feb)']
    })
    
    sns.set(style="whitegrid")
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    
    sns.barplot(x='Season', y='y1', hue='BMP', data=GWWs_eff_df, ax=axes[0])
    axes[0].set_title('y1')
    axes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=90)  # Rotate x-axis labels
    
    sns.barplot(x='Season', y='y2', hue='BMP', data=GWWs_eff_df, ax=axes[1])
    axes[1].set_title('y2')
    axes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=90)  # Rotate x-axis labels
    
    plt.tight_layout()
    plt.show()