【问题标题】:Different colors for points and line in Seaborn regplotSeaborn regplot中点和线的不同颜色
【发布时间】:2018-06-17 04:10:20
【问题描述】:

Seaborn's regplot documentation 中列出的所有示例都显示相同颜色的点和回归线。更改 color 参数会同时更改。如何为点设置不同的颜色作为线?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    你是对的,color 参数改变了所有的情节元素。但是,如果您阅读了documentation中相关句子的最后一位:

    颜色:matplotlib 颜色

    应用于所有绘图元素的颜色;将被颜色取代 传入scatter_kwsline_kws

    因此,使用scatter_kwsline_kws 我们可以单独更改它们的颜色。以文档中给出的第一个示例为例:

    import seaborn as sns
    
    tips = sns.load_dataset("tips")
    ax = sns.regplot(x="total_bill", y="tip", data=tips,
                     scatter_kws={"color": "black"}, line_kws={"color": "red"})
    
    plt.show()
    

    给予:

    【讨论】:

      【解决方案2】:

      你已经有了一个很好的答案。 DavidG 建议使用 line_kwsscatter_kws 的副作用是回归线和置信区间颜色相同(尽管 ci 是 alpha-ed)。这是一种具有不同颜色的方法。如果有更好的方法,我想知道!

      创建一个 seaborn FacetGrid,然后使用 map() 函数添加图层:

      import pandas 
      x = [5, 3, 6, 3, 4, 4, 6, 8]
      y = [13, 15, 7, 12, 13, 11, 9, 5]
      d = pandas.DataFrame({'x':x, 'y': y})
      import seaborn
      import matplotlib.pyplot as plt 
      seaborn.set(style = 'whitegrid')
      p = seaborn.FacetGrid(d, size = 4, aspect = 1.5) 
      p.map(plt.scatter, 'x', 'y', color = 'red')
      p.map(seaborn.regplot, 'x', 'y', scatter = False, ci = 95, 
          fit_reg = True, color = 'blue') 
      p.map(seaborn.regplot, 'x', 'y', scatter = False, ci = 0, 
          fit_reg = True, color = 'darkgreen')
      p.set(xlim = (2, 9)) 
      p.set(ylim = (2, 17)) 
      p.savefig('xy-regression-ci.pdf', bbox_inches='tight')
      

      我受到了question的启发

      顺便说一句(题外话):尽早设置图形的大小,因为通常的方法在这里似乎不适用。

      # set figure size here by combining size and aspect:
      seaborn.FacetGrid(d, size=4, aspect=1.5) 
      
      # usual tricks below do not work with FacetGrid?
      p.set_size_inches(8,4)
      seaborn.set(rc={'figure.figsize':(8,4)})
      rcParams['figure.figsize'] = 8,4
      

      【讨论】:

        【解决方案3】:

        我能够使用 PatrickT 的答案获得不同的颜色,而无需 FacetGrid。我想我会提到它。

        import pandas as pd
        x = [5, 3, 6, 3, 4, 4, 6, 8]
        y = [13, 15, 7, 12, 13, 11, 9, 5]
        d = pd.DataFrame({'x':x, 'y':y})
        import seaborn as sns
        import matplotlib.pyplot as plt 
        sns.set(style = 'whitegrid')
        plt.scatter(x, y, color = 'red')
        sns.regplot(data=d, x='x', y='y', scatter = False, ci = 95, 
            fit_reg = True, color = 'blue') 
        sns.regplot(data=d, x='x', y='y', scatter = False, ci = 0, 
            fit_reg = True, color = 'darkgreen')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-04
          相关资源
          最近更新 更多