Search code examples
pythonmatplotlibstatsmodels

How to draw plots created by statsmodels plotting functions in the same figure


I have the following code

from statsmodels.graphics.factorplots import interaction_plot
import statsmodels.api as sm
import matplotlib.pyplot as plt

# ...

fig1 = interaction_plot(a, b, c, colors=['red', 'blue'], markers=['D', '^'], ms=10)
fig2 = sm.qqplot(model.resid, line='s')
plt.show()

which produces Figure 1 and Figure 2 each in a separate window.

How can I draw those two figures in the same window?


Solution

  • While you'll find lots of resources about creating two or more subplots in matplotlib, the question here is more specifically asking to create two plots produced by statsmodels.graphics.factorplots.interaction_plot and statsmodels.api.qqplot into the same figure.

    Both of those functions take an argument ax to which you can supply a matplotlib axes, such that the plot is produced inside of this axes.

    from statsmodels.graphics.factorplots import interaction_plot
    import statsmodels.api as sm
    import matplotlib.pyplot as plt
    
    # ...
    
    fig, (ax, ax2) = plt.subplots(nrows=2) # create two subplots, one in each row
    
    interaction_plot(a, b, c, colors=['red', 'blue'], markers=['D', '^'], ms=10, ax=ax)
    sm.qqplot(model.resid, line='s', ax=ax2)
    
    plt.show()