简体   繁体   中英

How to remove stemline(s) from a matplotlib stem plot?

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.

You can use obj.remove() to remove objects from a plot after they have been plot, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM