如何在seaborn regplot中使用x_bins修复图例颜色?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在seaborn regplot中使用x_bins修复图例颜色?相关的知识,希望对你有一定的参考价值。

当我在参数中包含x_bins时,Seaborn regplot会停止将图例颜色与线条颜色匹配。它工作正常,直到我添加x_bins然后多色的图例失去其颜色差异。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
import pandas as pd
import seaborn as sns

data=pd.DataFrame("VarX" : np.arange(10), 
                   'VarY1': np.random.rand(10),
                   'VarY2': np.random.rand(10),
                   'VarY3': np.random.rand(10))

fig = plt.figure(figsize=(10,6))
sns.regplot(x='VarX', y='VarY1', data=data, x_bins=10)
sns.regplot(x='VarX', y='VarY2', data=data, x_bins=10)
sns.regplot(x='VarX', y='VarY3', data=data, x_bins=10)
fig.legend(labels=['First','Second','Third'])
plt.show()

enter image description here

答案

Seaborn有自己的传奇概念,经常与默认的matplotlib传说冲突。

为了保持seaborn的思维方式,你可以使用lmplot来让它自动生成图例。这需要稍微重新整形输入数据。

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
import pandas as pd


data=pd.DataFrame("VarX" : np.arange(10), 
                   'VarY1': np.random.rand(10),
                   'VarY2': np.random.rand(10),
                   'VarY3': np.random.rand(10))

df = data.set_index("VarX")
df.columns = ['First','Second','Third']
df = df.stack().rename_axis(['VarX','Ycategory']).rename('VarY').reset_index()


sns.lmplot(x="VarX", y="VarY", hue="Ycategory", data = df, x_bins=10)

plt.show()

enter image description here

以上是关于如何在seaborn regplot中使用x_bins修复图例颜色?的主要内容,如果未能解决你的问题,请参考以下文章

有xticks在Pandas的Seaborn regplot中显示月份

使用 seaborn regplot 的扩展回归线

Seaborn regplot 使用 datetime64 作为 x 轴

Seaborn使用regplot函数可视化散点图并添加回归曲线以及回归线对应的置信区间(Scatter plot with regression line)

TypeError:在绘制 seaborn.regplot 时,无法根据规则“安全”将数组数据从 dtype('int64') 转换为 dtype('int32')

Seaborn使用regplot函数可视化散点图并添加回归曲线以及回归线对应的置信区间(Scatter plot with regression line)