1

Here is an example script to create a stem plot in matplotlib.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np

# returns 10 evenly spaced samples from 0.1 to 2*PI
x = np.linspace(0.1, 2 * np.pi, 10)

fig, ax = plt.subplots( figsize=(4.,3.), constrained_layout=True)
markerline, stemline, baseline = ax.stem(x, np.cos(x), '-.', use_line_collection=True)
markerline1, stemline1, baseline1 = ax.stem(x, np.cos(x*5), '-', use_line_collection=True)

plt.setp(baseline, color='black', linewidth=2)
plt.setp(baseline1, color='black', linewidth=2)
plt.setp( stemline, color="green" )
plt.setp( stemline1, color="red" )

plt.show()

Q1. After creating these plots, I would like to remove for example markerline1, stemline1, baseline1. How do I remove them?

Q2. If I would like to remove the entire stem plot from ax without affecting other settings of ax, how do I do so? I found that ax.clear() removes everything from ax.

According to matplotlib,

UserWarning: In Matplotlib 3.3 individual lines on a stem plot will be added as a LineCollection instead of individual lines.

Also, LineCollection appears to have an attribute called segment that contains the x,y info of all the stem lines.

Q3. How do I get the LineCollection object from ax or fig? I am exploring if amending the LineCollection object is a method to answer my first question.

Sun Bear
  • 7,594
  • 11
  • 56
  • 102
  • 1
    Q1: You can use obj.remove()` to remove objects from a plot after they have been plot, i.e `markerline1.remove()`, etc. More details here :https://stackoverflow.com/questions/4981815/how-to-remove-lines-in-a-matplotlib-plot This can be extended to Q2 by looping over all the objects you have on your plot if you named them before. – Liris Mar 10 '20 at 13:52
  • @Liris Thanks. `.remove()` works when `use_line_collection=True` but not when `use_line_collection=False`. Pls put up your answer in the Answer Section so that I can accept it. cheers ;) – Sun Bear Mar 10 '20 at 16:18

1 Answers1

0

You can use obj.remove() to remove objects from a plot after they have been plot, i.e markerline1.remove(), etc.

More details here

This can be extended to Q2 by looping over all the objects you have on your plot if you named them before.

Liris
  • 1,399
  • 3
  • 11
  • 29