Anake
Anake

Reputation: 7659

matplotlib cancel legend on axes object

I am using an external module which automatically adds a legend to the plot. I would like to know if there is a way of turning off the legend, something like ax.set_legend(False).

I could fix it by hacking the module but I would rather not do that.

example:

 f = plt.figure()
 ax = f.add_subplot(111)

 externalfunction(ax)

 # in the function ax.legend() has been called
 # would like to turn off the legend here

 plt.show()

Update:

I have raised a github issue for this https://github.com/matplotlib/matplotlib/issues/2792

Upvotes: 3

Views: 490

Answers (2)

mwaskom
mwaskom

Reputation: 49022

This can also be accomplished by setting the legend_ attribute of the axis to None. Note the trailing underscore. E.g.

x, y = np.random.randn(2, 30)
ax = plt.gca()
ax.plot(x, y, label="data")
ax.legend()
ax.legend_ = None

It sounds like future matplotlib versions will have a more officially-sanctioned method for removing the axis, but this should work in the meantime/if stuck on an older version.

Upvotes: 4

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17475

You need to change the visibility of your legend, try this: ax.legend().set_visible(False)

Upvotes: 3

Related Questions