`AttributeError`在使用tikzplotlib绘制图例时发生。

huangapple go评论66阅读模式
英文:

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:

# 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")

希望这对您有所帮助。

英文:

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")

答案1

得分: 11

嘿,我有/曾经有相同的问题,

问题是,使用matplotlib 3.6时,界面发生了变化。GitHub上已经有一个修复(#558),但看起来目前似乎不会有任何改变。不过,GitHub上有一个针对此问题的解决方法(问题)。它运作得相当好。希望这个答案很快就会过时。

为了完整起见,我将再次在此添加代码。

def tikzplotlib_fix_ncols(obj):
    """
    解决matplotlib 3.6将图例的 _ncol 重命名为 _ncols 而破坏 tikzplotlib 的问题
    """
    if hasattr(obj, "_ncols"):
        obj._ncol = obj._ncols
    for child in obj.get_children():
        tikzplotlib_fix_ncols(child)

免责声明:这不是我的代码。但这个问题可能非常令人讨厌,这就是我在这里分享代码的原因。作者是 st--

英文:

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--

huangapple
  • 本文由 发表于 2023年3月31日 23:27:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定