0

I am trying to find a way in matplotlib to draw a lineplot, except that I don't want to draw a line between points. Instead I want to draw a perpendicular line between each of my points and the x axis.

When I do a standard plot, I obtain the following :

import numpy as np
import matplotlib.pyplot as plt
data = np.array([0,1,3,2,3,1,4])
plt.plot(data)
plt.xlim([-0.2,6.2])
plt.ylim([-0.2,5])

enter image description here

Instead I want to obtain the following :

enter image description here

Any ideas how to do this ? Thanks

Gabriel
  • 857
  • 10
  • 14
  • `plt.bar(range(data.size), data, width=0.1, color='crimson')` – JohanC May 11 '20 at 08:17
  • 1
    A stem plot is another option: `plt.stem(data, linefmt='r-', markerfmt='o')`. (To change linewidth: see [this post](https://stackoverflow.com/questions/32953201/matplotlib-change-stem-plot-linewidth)) – JohanC May 11 '20 at 08:32
  • Thanks, stem plot is exactly what I was looking for. – Gabriel May 11 '20 at 09:35

1 Answers1

1

There are two other options apart from stem and bar chart is the following using vlines() and LineCollection()


Option 1 -- Using vlines()

for x, y in enumerate(data):
    plt.vlines(x=x, ymin=0, ymax=y, color='r')

Or in a single line without using loops

plt.vlines(x=range(data.size), ymin=0, ymax=data, color='r')

Option 2 -- Using LineCollection()

from matplotlib.collections import LineCollection

lines = [[(x, 0), (x, y)] for x, y in enumerate(data)]
linesCol = LineCollection(lines, linewidths=3, color='r')

fig, ax = plt.subplots()
ax.add_collection(linesCol)
plt.scatter(range(len(data)), data, s=0)

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Thanks for your valuable input. Though stem plot is perfect for my case, the LineCollection solution seems highly customizable. – Gabriel May 11 '20 at 09:42
  • 1
    Why a loop for `plt.vlines` and not in one command`plt.vlines(x=range(data.size), ymin=0, ymax=data, color='r')`? – JohanC May 11 '20 at 10:00
  • @JohanC : Thanks for the tip. I will edit your suggestion to the answer. – Sheldore May 11 '20 at 10:13