Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib how to draw vertical line between two Y points

I have 2 y points for each x points. I can draw the plot with this code:

import matplotlib.pyplot as plt

x = [0, 2, 4, 6]
y = [(1, 5), (1, 3), (2, 4), (2, 7)]


plt.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
plt.plot(x, [j for (i,j) in y], 'bo', markersize = 4)

plt.xlim(xmin=-3, xmax=10)
plt.ylim(ymin=-1, ymax=10)

plt.xlabel('ID')
plt.ylabel('Class')
plt.show()

This is the output:

Sample Plot

How can I draw a thin line connecting each y point pair? Desired output is:

Desired Output

like image 803
iso_9001_ Avatar asked Jan 03 '20 17:01

iso_9001_


People also ask

How do you plot a vertical straight line in Python?

To plot a vertical line with pyplot, you can use the axvline() function. In this syntax: x is the coordinate for the x-axis. This point is from where the line would be generated vertically. ymin is the bottom of the plot; ymax is the top of the plot.

How do I create a vertical and horizontal line in matplotlib?

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].


2 Answers

just add plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='black')

enter image description here

like image 79
Guinther Kovalski Avatar answered Nov 05 '22 15:11

Guinther Kovalski


Alternatively, you can also use LineCollection. The solution below is adapted from this answer.

from matplotlib import collections as matcoll

x = [0, 2, 4, 6]
y = [(1, 5), (1, 3), (2, 4), (2, 7)]

lines = []
for i, j in zip(x,y):
    pair = [(i, j[0]), (i, j[1])]
    lines.append(pair)

linecoll = matcoll.LineCollection(lines, colors='k')

fig, ax = plt.subplots()
ax.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
ax.plot(x, [j for (i,j) in y], 'bo', markersize = 4)
ax.add_collection(linecoll)

enter image description here

like image 32
Sheldore Avatar answered Nov 05 '22 15:11

Sheldore