具有可变线宽的 Matplotlib 图 [英] Matplotlib plot with variable line width

查看:41
本文介绍了具有可变线宽的 Matplotlib 图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to plot a line with variable line width in matplotlib? For example:

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)

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

This doesn't work because linewidth expects a scalar.

注意:我知道 *fill_between()* 和 *fill_betweenx()*.因为这些只填充 x 或 y 方向,所以这些对你有一条斜线的情况不公平.填充始终与线垂直是可取的.这就是寻求可变宽度线的原因.

Note: I'm aware of *fill_between()* and *fill_betweenx()*. Because these only fill in x or y direction, these do not do justice to cases where you have a slanted line. It is desirable for the fill to always be normal to the line. That is why a variable width line is sought.

推荐答案

Use LineCollections.按照this Matplotlib 示例

Use LineCollections. A way to do it along the lines of this Matplotlib example is

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

这篇关于具有可变线宽的 Matplotlib 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆