Search code examples
pythonmatplotlibseabornsubplot

Plot does not show at ax[0] in Python


I would like to create a side by side figure. I use matplotlib and Seaborn package for this; however, I just can't seem to fit a plot into the first box. Can anyone please tell me what part of my code is wrong?

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# create a test dataframe
test = pd.DataFrame({
    'genre': ['var1','var2'],
    'left plot': [1,3],
    'right plot': [2,4]})

# Making a figure with two subplots 
fig, ax = plt.subplots(1,2)   # 2 plots
fig.set_figheight(5)
fig.set_figwidth(8) 

# Plots
ax[0] = sns.barplot(x = 'left plot',y = 'genre',data = test)  # this is where the problem is
ax[1] = sns.barplot(x = 'right plot',y = 'genre',data = test) 
    
# show plot
plt.show()

enter image description here

The "Left plot" is missing; even though I already specified ax[0] for it. Please help :"(


Solution

  • Specifying the ax when creating the sns plots should solve your problem :)

    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd
    
    # create a test dataframe
    test = pd.DataFrame({
        'genre': ['var1','var2'],
        'left plot': [1,3],
        'right plot': [2,4]})
    
    # Making a figure with two subplots 
    fig, ax = plt.subplots(1,2)   # 2 plots
    fig.set_figheight(5)
    fig.set_figwidth(8) 
    
    # Plots
    sns.barplot(x = 'left plot',y = 'genre',data = test, ax=ax[0])  # this is where the problem is
    sns.barplot(x = 'right plot',y = 'genre',data = test, ax=ax[1]) 
    
    # show plot
    plt.show()