小编典典

具有可变线宽的Matplotlib图

python

是否可以在matplotlib中绘制线宽可变的线?例如:

from pylab import *
x = [1, 2, 3, 4, 5]
y = [1, 2, 2, 0, 0]
width = [.5, 1, 1.5, .75, .75]

plot(x, y, linewidth=width)

这不起作用,因为线宽需要标量。

注意:我知道 fill_between() fill_betweenx()。因为这些仅填充x或y方向,所以对于您有斜线的情况而言,这些不正确。希望填充始终垂直于线。这就是为什么要寻找可变宽度的线。


阅读 189

收藏
2020-12-20

共1个答案

小编典典

使用LineCollections。遵循此Matplotlib示例的一种方法是

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
x = np.linspace(0,4*np.pi,10000)
y = np.cos(x)
lwidths=1+x[:-1]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, linewidths=lwidths,color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,4*np.pi)
a.set_ylim(-1.1,1.1)
fig.show()
2020-12-20