Home > Software engineering >  delete legend from statsmodels interaction_plot
delete legend from statsmodels interaction_plot

Time:06-08

I use the interaction_plot from statsmodels. I would like to add a legend, but the interaction_plot has its own legend, so that i get two legends. An example:

import numpy as np
np.random.seed(12345)
weight = np.random.randint(1,4,size=60)
duration = np.random.randint(1,3,size=60)
days = np.log(np.random.randint(1,30, size=60))
fig = interaction_plot(weight, duration, days,
             colors=['red','blue'], markers=['D','^'], ms=10)
import matplotlib.pyplot as plt
fig.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fancybox=True, shadow=True)
plt.show()

enter image description here

How do i delete the original legend?

CodePudding user response:

This function returns a figure with one axes, so you need to retrieve it and remove its legend:

fig = interaction_plot(weight, duration, days,
             colors=['red','blue'], markers=['D','^'], ms=10)

# this is what I added
fig.get_axes()[0].get_legend().remove()

fig.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fancybox=True, shadow=True)

If you are using a version of matplotlib older than 1.4.0, then replace that line with fig.get_axes()[0].legend_ = None.

  • Related