使用matplotlib在Python中绘制粗带

5 投票
1 回答
7706 浏览
提问于 2025-04-18 12:40

我想用Python的matplotlib库画一条线,这条线的粗细是会变化的。

为了更清楚,我有一个变量:

import matplotlib.pyplot as P 
import numpy as N

x_value = N.arange(0,10,1)
y_value = N.random.rand(10)
bandwidth = N.random.rand(10)*10
P.plot(x_value,y_value,bandwidth)

我想用x_value和y_value来画这条线,线的粗细会根据x_value的位置变化,这个变化由一个叫做bandwidth的向量来决定。

我想到的一个可能的解决办法是先画出上下两条线(也就是说,我可以用y_value[index]加上或减去bandwidth[index]/2来得到这两条线)。

然后我可以尝试填充这两条线之间的空间(怎么填充呢?)

如果你有任何建议,请告诉我。

谢谢,

Samuel。

1 个回答

7

你可以使用 fill_between 来实现这个效果。

比如说,如果你想让一半的 bandwidth 在上面,另一半在下面(同时还要用 plot 绘制原始线条):

在这里输入图片描述

import matplotlib.pyplot as P 
import numpy as N

x_value = N.arange(0,10,1)
y_value = N.random.rand(10)
bandwidth = N.random.rand(10)*10
print bandwidth
P.fill_between(x_value, y_value+bandwidth/2, y_value-bandwidth/2, alpha=.5)
P.plot(x_value,y_value)
P.show()

撰写回答