python - 扩展 matplotlib Line2D 类

标签 python class matplotlib

my answerthis question我尝试扩展 Line2D.draw 方法,以便它可以与 plot 一起使用。

所以我将 matplotlib.lines.Line2D 更改为我的 Line2D 扩展名:

import matplotlib.lines
import matplotlib.pyplot as plt
import matplotlib.patches as pt


class Line2D(matplotlib.lines.Line2D):
    def draw(self, rdr):
        super().draw(rdr)
        xy = self.get_xydata()
        start, end = xy[0], xy[-1]
        r = pt.Rectangle((start[0] - .05, start[1] - .05), .1, .1,
                         color=self.get_color(),
                         fill=None)
        plt.gca().add_patch(r)
        c = pt.Ellipse(end, .05, .05,
                       color=self.get_color(),
                       fill=True)
        plt.gca().add_patch(c)


fig = plt.figure()
ax = fig.add_subplot()
rg = [-.5, 1.5]
ax.set_xlim(rg)
ax.set_ylim(rg)


original_line2D = matplotlib.lines.Line2D
matplotlib.lines.Line2D = Line2D

plt.plot([0, 1], [1, 0], "r--")

plt.show()

我得到了这个结果,我猜 plt.plot 是内部使用的......但是如何避免这些鬼图?

enter image description here

最佳答案

我认为您可以使用您的线条,但您应该将其重置为 matplotlib 的原始 Line2D。例如:

fig = plt.figure()
ax = fig.add_subplot()
rg = [-.5, 1.5]
ax.set_xlim(rg)
ax.set_ylim(rg)

original_line2D = matplotlib.lines.Line2D
matplotlib.lines.Line2D = MyLine2D

plt.plot([0, 1], [1, 0], "r--")
matplotlib.lines.Line2D = original_line2D
plt.plot([1, 0], [1, 1], "g")
plt.show()

删除最后一行(绿色),按预期工作。

enter image description here

关于python - 扩展 matplotlib Line2D 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71874493/

相关文章:

python - python中输入过大如何处理?

python - Django VMware 设备

python - 使用 smtplib 从 Gmail 接收回复 - Python

python - matplotlib 轴对象究竟是什么?

python - 在 matplotlib 中重置已绘制散点的点

python - 为什么 pyplot.show() 不起作用?

Python:使用py2exe编译时出错

r - `...` 是什么类型的对象?

java - 使用额外参数扩展类

python - 如何在类中调用函数?