具有可变线宽的Matplotlib图

Ham*_*mid 31 python plot matplotlib

是否可以在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)
Run Code Online (Sandbox Code Playgroud)

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

注意:我知道*fill_between()*和*fill_betweenx()*.因为这些只能填充x或y方向,所以这些不适用于有斜线的情况.希望填充总是垂直于线.这就是寻求可变宽度线的原因.

gg3*_*349 67

使用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()
Run Code Online (Sandbox Code Playgroud)

产量

  • 根本不是我想要的,但这很酷,所以我投票:) (7认同)

小智 6

Giulio Ghirardo 的答案的另一种方法是将线分成几段,您可以使用 matplotlib 的内置 scatter 函数,该函数通过使用圆圈来构造线:

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0,10,10000)
y = 2 - 0.5*np.abs(x-4)
lwidths = (1+x)**2 # scatter 'o' marker size is specified by area not radius 
plt.scatter(x,y, s=lwidths, color='blue')
plt.xlim(0,9)
plt.ylim(0,2.1)
plt.show()
Run Code Online (Sandbox Code Playgroud)

根据我的经验,我发现将线分割成段有两个问题:

  1. 出于某种原因,这些段总是被非常细的白线分开。当使用大量线段时,这些线的颜色会与线段的颜色混合。因此,线条的颜色与预期的颜色不同。

  2. 它不能很好地处理非常尖锐的不连续性。