Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError occurs with tikzplotlib when legend is plotted

I am trying to save a figure using tikzplotlib. However, I am encountering an AttributeError: 'Legend' object has no attribute '_ncol'. I am currently using tikzplotlib version 0.10.1 and matplotlib version 3.7.0. Without using "plt.legend()" everything works.

Below is an example that is not working:

import numpy as np
import matplotlib.pyplot as plt
import tikzplotlib

# Data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Plotting
plt.figure()
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
plt.plot(x, y3, label='tan(x)')
plt.legend()

# Save as TikZ file
tikzplotlib.save("plot.tikz")

like image 493
Kuba1623 Avatar asked Jun 13 '26 01:06

Kuba1623


1 Answers

Hey I have/had the same problem,

the problem is that with matplotlib 3.6 the interface changed. There is already a fix (#558) for tikzplotlib on GitHub, but it looks like nothing will happen for now. However, there is a workaround for the issue on GitHub (Issue). It works quite well. I hope that this answer will soon become obsolete.

For the sake of completeness, I'll add the code here again.

def tikzplotlib_fix_ncols(obj):
    """
    workaround for matplotlib 3.6 renamed legend's _ncol to _ncols, which breaks tikzplotlib
    """
    if hasattr(obj, "_ncols"):
        obj._ncol = obj._ncols
    for child in obj.get_children():
        tikzplotlib_fix_ncols(child)

Disclaimer: This is not my code. But this problem can be very annoying and that's why I'm sharing the code here. The author is st--

like image 90
Cutyno Avatar answered Jun 15 '26 15:06

Cutyno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!