【问题标题】:matplotlib change linewidth on line segments, using listmatplotlib 使用列表更改线段上的线宽
【发布时间】:2013-11-08 23:49:02
【问题描述】:

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

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

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

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

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

谢谢

【问题讨论】:

  • 你能发布你的代码吗?如果要绘制线条,可以循环遍历每一行,并为每一行设置线宽。

标签: python matplotlib


【解决方案1】:

基本上,您有两种选择。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-10-09
  • 2015-03-27
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 2012-03-31
  • 2018-04-02
  • 1970-01-01
相关资源
最近更新 更多