ajsp
ajsp

Reputation: 2670

Horizontal lines with LineCollection in matplotlib?

How do I add, or create horizontal lines with LineCollection in matplotlib? I am trying to make an animation faster, and don't want to go over old ground, but basically I am trying to avoid using axhline in a for loop to construct an array of lines. Hence it was recommended that I try LineCollection. But so far I can only get to plot a series.

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9]
y = [42,13,24,14,74,45,22,44,77]

lc = LineCollection(zip(x,y),color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,10)
a.set_ylim(0,100)
plt.show()

And if I add the coordinates explicitly, for example:

x = [(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9)]
y = [(42,42),(13,13),(24,24),(14,14),(74,74),(45,45),(22,22),(44,44),(77,77)]

I get the following plot? enter image description here

How is that even possible?

Upvotes: 1

Views: 1371

Answers (2)

Zaraki Kenpachi
Zaraki Kenpachi

Reputation: 5730

Here you go:

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

# set x coordinates range
N = 10
x = np.arange(1, N, 1)

# create set od data for lines
number_of_lines = 6
base_array = np.ones(N-1)
lines_list = [base_array + i for i in range(number_of_lines)]

# set plot limits
fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(lines_list)-1, np.max(lines_list)+1)

# load sequences of aray pairs (x,y)
line_segments = LineCollection([np.column_stack([x, y]) for y in lines_list], linestyles='solid')
line_segments.set_array(x)
ax.add_collection(line_segments)
plt.show()

Output:

enter image description here

Upvotes: 2

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339300

One options is this:

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt


y = [42,13,24,14,74,45,22,44,77]
segs = np.zeros((len(y), 2, 2))
segs[:,:,1] = np.c_[y,y]
segs[:,1,0] = np.ones(len(y))


fig, ax = plt.subplots()
lc = LineCollection(segs,color='blue', transform=ax.get_yaxis_transform())
ax.add_collection(lc)
ax.set_xlim(0,10)
ax.set_ylim(0,100)
plt.show()

Upvotes: 4

Related Questions