AttributeError: module 'matplotlib.pyplot' has no attribute 'PathPatch'上述代码报错,怎么解决
时间: 2024-10-18 12:11:55 浏览: 19
这个错误提示`AttributeError: module 'matplotlib.pyplot' has no attribute 'PathPatch'`意味着在当前的matplotlib版本中,`pyplot`模块并没有`PathPatch`属性。`PathPatch`通常在`patches`模块中找到。
你需要替换掉`plt.PathPatch`,将其改为`plt.patches.PathPatch`,因为`patches`模块包含了创建路径对象的功能。修正后的代码应该是这样的:
```python
import matplotlib.pyplot as plt
from matplotlib.path import Path
import numpy as np
def heart_curve(x):
return (x**3 - x) / 4
# 定义心形路径
verts = [(0, 0), (heart_curve(0.707), 0),
(heart_curve(0.707), -0.707), (0, -1),
(-heart_curve(0.707), -0.707), (0, 0)]
codes = [Path.MOVETO,
Path.CURVE4, Path.CURVE4,
Path.LINETO, Path.CURVE4, Path.CLOSEPOLY]
path = Path(verts, codes)
fig, ax = plt.subplots()
patch = plt.patches.PathPatch(path)
ax.add_patch(patch)
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
plt.show()
阅读全文