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

如何在seaborn lineplot上绘制虚线?

  •  4
  • crash  · 技术社区  · 8 年前

    我只是想用seaborn画一条虚线。这是我正在使用的代码和输出

    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    
    n = 11
    x = np.linspace(0,2,n)
    y = np.sin(2*np.pi*x)
    
    sns.lineplot(x,y, linestyle='--')
    plt.show()
    

    enter image description here

    我做错什么了?谢谢

    2 回复  |  直到 8 年前
        1
  •  14
  •   DavidG    8 年前

    看来 linestyle= 争论不起作用 lineplot() ,和论点 dashes=

    一个相对简单的方法是使用 ax.lines

    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    
    n = 11
    x = np.linspace(0,2,n)
    y = np.sin(2*np.pi*x)
    
    ax = sns.lineplot(x,y)
    
    # Might need to loop through the list if there are multiple lines on the plot
    ax.lines[0].set_linestyle("--")
    
    plt.show()
    

    enter image description here

    更新:

    看起来 dashes

    n = 100
    x = np.linspace(0,4,n)
    y1 = np.sin(2*np.pi*x)
    y2 = np.cos(2*np.pi*x)
    
    df = pd.DataFrame(np.c_[y1, y2]) # modified @Elliots dataframe production
    
    ax = sns.lineplot(data=df, dashes=[(2, 2), (2, 2)])
    plt.show()
    

    enter image description here

        2
  •  1
  •   Elliot Jeremy Allen    8 年前

    你实际上在用 lineplot 走错了路。你的简化案例更适合 matplotlib 的 plot seaborn . 海伯恩 更多的是为了在脚本中减少直接干预的情况下使绘图更具可读性,并且通常在处理 pandas

    例如

    import seaborn as sns
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    n = 100
    x = np.linspace(0,2,n)
    y1 = np.sin(2*np.pi*x)
    y2 = np.sin(4*np.pi*x)
    y3 = np.sin(6*np.pi*x)
    
    df = pd.DataFrame(np.c_[y1, y2, y3], index=x)
    
    ax = sns.lineplot(data=df)
    plt.show()
    

    产量

    enter image description here

    至于如何按照你想要的方式设置你想要显示的变量的样式,我不知道该如何处理。