首页 > 解决方案 > 使 matplotlib 图部分不可见

问题描述

看看这个漂亮的图表。

在此处输入图像描述

在 matplotlib 中有没有办法使红色和绿色图形的一部分不可见(其中 f(x)=0)?

不仅是那些,还有平坦部分连接到正弦曲线的单线段。

基本上,是否可以告诉 matplotlib 仅在某个间隔上绘制图形而不绘制其余部分(反之亦然)?

标签: pythonmatplotlib

解决方案


np.nan您可以尝试使用如下所示替换您的兴趣点:

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

在此处输入图像描述


推荐阅读