在 my answer至 this 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
是内部使用的......但是如何避免这些鬼图?
最佳答案
我认为您可以使用您的线条,但您应该将其重置为 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()
删除最后一行(绿色),按预期工作。
关于python - 扩展 matplotlib Line2D 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71874493/