Seaborn regp中点和线的不同颜色

2024-05-12 18:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 示例参数颜色documentationseaborncolor回归线
2条回答

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

创建一个seabornFacetGrid,然后使用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

enter image description here

结束语(离题):尽早设置图形的大小,因为通常的方法似乎不适用于这里。

# 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

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

color : matplotlib color

Color to apply to all plot elements; will be superseded by colors passed in scatter_kws or line_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()

给出:

enter image description here

相关问题 更多 >