Search code examples
pythonmatplotlibcode-documentation

In matplotlib legend how to define number of columns in horizontal legend (ncol or ncols)?


I was having a difficult time fixing the display of a legend in one matplotlib figure, and then I noticed that maybe there is an incongruence in matplotlib documentation, or I am not searching in the right place. In my code, I can only make a horizontal legend work if I define ncol, as in the following example from matplotlib demo:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1)

# Plot the lines y=x**n for n=1..4.
ax = plt.subplot(2, 1, 1)
for n in range(1, 5):
    plt.plot(x, x**n, label="n={0}".format(n))
plt.legend(loc="upper left", bbox_to_anchor=[0, 1],
           ncol=2, shadow=True, title="Legend", fancybox=True)
ax.get_legend().get_title().set_color("red")

However, also in matplotlib documentation, they state that ncols(and not ncol) is the right parameter name. I also tested with alignment parameter and I got the same error as if I use ncols: __init__() got an unexpected keyword argument 'alignment'.

I'm not sure if this is an error or I am missing something here. I'm using matplotlib 3.4.3.


Solution

  • I have always used ncol without problems but you are correct. If you check on the documentation of the latest version of matplotlib 3.6.0 indicates ncols, this realase is quite recent (15 September 2022) and indicates the rename of the parameter (release update). Nevertheless, probably both arguments are currently valid, since the last parameter defined in the function is still ncol. enter image description here

    For me it seems as ncol parameter will be deprecated in the future and ncols will be the only one used.

    Notice that the parameter names change within versions of the packages. if you check older versions of matplotlib 3.2.0 ncol was the parameter defined.