Making a matplotlib graph partially invisible

Viewed 787

Look at this pretty graph.

enter image description here

Is there a way, in matplotlib, to make parts of the red and green graph invisible (where f(x)=0)?

Not just those, but also the single line segment where the flat part connects to the sine curve.

Basically, is it possible to tell matplotlib to only plot graph on a certain interval and not draw the rest (or vice versa)?

1 Answers

You could try replacing your points of interest with np.nan as shown below:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# here is some example data because none was provided in the question;
# it is a quadratic from x=-5:5
x = np.arange(-5, 6)
s = pd.Series(x**2, index=x)

# replace all y values less than 4 with np.nan and store in a new Series object
s_mod = s.apply(lambda y: np.nan if y < 4 else y)

# plot the modified data with the original data
fig, ax = plt.subplots()
s.plot(marker='o', markersize=16, ax=ax, label='original')
s_mod.plot(marker='s', ax=ax, label='modified')
ax.legend()

fig  # displays as follows

enter image description here

Related