如何在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()

http://img4.mukewang.com/61d5072900012e8b07520431.jpg

临摹微笑
浏览 190回答 1
1回答

互换的青春

Seaborn 有自己的图例概念,它经常与默认的 matplotlib 图例冲突。为了保持seaborn的思维方式,你可以使用lmplot它,让它自动生成图例。这需要稍微重塑输入数据。import seaborn as snsimport matplotlib.pyplot as pltimport numpy as np; np.random.seed(1)import pandas as pddata=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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python