How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?

后端 未结 2 400
耶瑟儿~
耶瑟儿~ 2021-01-12 05:51

I have two different sets of data with a common index, and I want to represent the first one as a barplot and the second one as a lineplot in the same graph. My current appr

2条回答
  •  忘掉有多难
    2021-01-12 06:43

    You can use twinx() method along with seaborn to create a seperate y-axis, one for the lineplot and the other for the barplot. To control the style of the plot (default style of seaborn is darkgrid), you can use set_style method and specify the preferred theme. If you set style=None it resets to white background without the gridlines. You can also try whitegrid. If you want to further customize the gridlines, you can do it on the axis level using the ax2.grid(False).

    import matplotlib
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    matplotlib.rc_file_defaults()
    ax1 = sns.set_style(style=None, rc=None )
    
    fig, ax1 = plt.subplots(figsize=(12,6))
    
    sns.lineplot(data = df['y_var_1'], marker='o', sort = False, ax=ax1)
    ax2 = ax1.twinx()
    
    sns.barplot(data = df, x='x_var', y='y_var_2', alpha=0.5, ax=ax2)
    

提交回复
热议问题