Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib change linewidth on line segments, using list

I would like to be able to change width of a line according to a list of values. For example if I have the following list to plot:

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

could I use the following list to set the linewidth?

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

It doesn't seem to be supported, but they say "anything is possible" so thought I would ask people with more experience (noob here).

Thanks

like image 206
greekgoddj Avatar asked Nov 08 '13 14:11

greekgoddj


1 Answers

Basically, you have two options.

  1. Use a LineCollection. In this case, your line widths will be in points, and the line width will be constant for each segment.
  2. Use a polygon (easiest with fill_between, but for complex curves you may need to create it directly). In this case, your line widths will be in data units and will vary linearly between each segment in your line.

Here are examples of both:

Line Collection Example


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

enter image description here

Polygon Example:


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

enter image description here

like image 193
Joe Kington Avatar answered Sep 18 '22 10:09

Joe Kington