5

我希望能够根据值列表更改线的宽度。例如,如果我要绘制以下列表:

a = [0.0, 1.0, 2.0, 3.0, 4.0]

我可以使用以下列表来设置线宽吗?

b = [1.0, 1.5, 3.0, 2.0, 1.0]

它似乎不受支持,但他们说“一切皆有可能”,所以我想我会问有更多经验的人(这里是菜鸟)。

谢谢

4

1 回答 1

11

基本上,您有两种选择。

  1. 使用LineCollection. 在这种情况下,您的线宽将以磅为单位,并且每个线段的线宽将是恒定的。
  2. 使用多边形(使用 最简单fill_between,但对于复杂曲线,您可能需要直接创建它)。在这种情况下,您的线宽将以数据单位为单位,并且将在您的线中的每个段之间线性变化。

以下是两者的示例:

行集合示例


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
np.random.seed(1977)

x = np.arange(10)
y = np.cos(x / np.pi)
width = 20 * np.random.random(x.shape)

# Create the line collection. Widths are in _points_!  A line collection
# consists of a series of segments, so we need to reformat the data slightly.
coords = zip(x, y)
lines = [(start, end) for start, end in zip(coords[:-1], coords[1:])]
lines = LineCollection(lines, linewidths=width)

fig, ax = plt.subplots()
ax.add_collection(lines)
ax.autoscale()
plt.show()

在此处输入图像描述

多边形示例:


import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)

x = np.arange(10)
y = np.cos(x / np.pi)
width = 0.5 * np.random.random(x.shape)

fig, ax = plt.subplots()
ax.fill_between(x, y - width/2, y + width/2)
plt.show()

在此处输入图像描述

于 2013-11-08T15:49:02.063 回答