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

2024-09-29 19:30:32 发布

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

Seaborn regplot在参数中包含x_bin时停止匹配图例颜色与线条颜色。它工作得很好,直到我添加x峎箱,然后多色传奇失去了它的颜色差异。

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


Tags: importdata颜色asnppltrandompd
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:32

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

相关问题 更多 >

    热门问题