代码之家  ›  专栏  ›  技术社区  ›  Karlovsky120

使matplotlib图形部分不可见

  •  0
  • Karlovsky120  · 技术社区  · 7 年前

    enter image description here

    在matplotlib中,是否有办法使红色和绿色图形的某些部分不可见(其中f(x)=0)?

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   jeschwar    7 年前

    你可以试着用 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
    

    enter image description here