Last active
February 9, 2025 21:37
-
-
Save mg98/50951c604599c1e493c1b79bdb4429f7 to your computer and use it in GitHub Desktop.
Quick fix for tikzplotlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
As the library `tikzplotlib` is not maintained anymore, errors may arise due to incompatibility. | |
I don't know to which Python or matplotlib version this solution extends, but I verified this code to work with | |
- Python 3.9 | |
- matplotlib==3.63 | |
- tikzplotlib==0.10.1 | |
- webcolors==1.12 | |
""" | |
import matplotlib.pyplot as plt | |
import tikzplotlib | |
# [FIX] AttributeError: 'Line2D' object has no attribute '_us_dashSeq' | |
from matplotlib.lines import Line2D | |
from matplotlib.legend import Legend | |
Line2D._us_dashSeq = property(lambda self: self._dash_pattern[1]) | |
Line2D._us_dashOffset = property(lambda self: self._dash_pattern[0]) | |
Legend._ncol = property(lambda self: self._ncols, lambda self, value: setattr(self, "_ncols", value)) | |
# [FIX] AttributeError: 'Legend' object has no attribute '_ncol' | |
def tikzplotlib_fix_ncols(obj): | |
if hasattr(obj, "_ncols"): | |
obj._ncol = obj._ncols | |
if hasattr(obj, 'gcf'): | |
fig = obj.gcf() | |
for ax in fig.get_axes(): | |
if hasattr(ax, 'legend_') and ax.legend_ is not None: | |
if hasattr(ax.legend_, "_ncols"): | |
ax.legend_._ncol = ax.legend_._ncols | |
else: | |
for child in obj.get_children(): | |
tikzplotlib_fix_ncols(child) | |
tikzplotlib_fix_ncols(plt) # or `tikzplotlib_fix_ncols(fig)` | |
# tikzplotlib.save('figure.tex', axis_width=r'\columnwidth', axis_height=r'6cm') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment