Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - Mathplotlib draw triangle with gradient fill

I have to draw a triangle in Python using mathplotlib.
This is how it should eventually look like:
image
My objective is, once drawn the triangle, to plot some points on it.

At the moment I can draw the triangle just fine:

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

But I can only fill it with a solid color. How do I add a gradient like shown in the picture?

Can some one help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is an example on the matplotlib page showing how to use a clip path for an image.
Adapting this to your case would give this:

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...