我必须使用 mathplotlib 在 Python 中绘制三角形。
This它最终应该是这样的:
我的目标是,绘制三角形后,在其上绘制一些点。
目前我可以很好地绘制三角形:
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.add_patch(Polygon([[0,0],[0,1],[1,0]], closed=True,fill=True))
ax.set_xlim((0,1))
ax.set_ylim((0,1))
plt.show()
但我只能用纯色填充它。如何添加如图所示的渐变?
谁能帮帮我?
最佳答案
有一个example on the matplotlib page显示如何使用图像的剪辑路径。
根据您的情况进行调整会得到:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
path = Path([[0,0],[0,1],[1,0],[0,0]])
patch = PathPatch(path, facecolor='none')
ax.add_patch(patch)
Z, Z2 = np.meshgrid(np.linspace(0,1), np.linspace(0,1))
im = plt.imshow(Z-Z2, interpolation='bilinear', cmap=plt.cm.RdYlGn,
origin='lower', extent=[0, 1, 0, 1],
clip_path=patch, clip_on=True)
im.set_clip_path(patch)
ax.set_xlim((0,1))
ax.set_ylim((0,1))
plt.show()
关于python - Matplotlib 绘制带渐变填充的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063542/