简体   繁体   English

seaborn 线图显示错误的图例

[英]seaborn lineplot shows wrong legend

I have a pandas dataframe with the following format:我有一个 pandas dataframe 格式如下:

TEILNR VALUE date
351    10    2019-01-01
833    20    2019-01-01
...
351   40    2020-05-01

which has the dtypes:它具有dtypes:

TEILNR object
VALUE   int64
date object

when I use the following command for plotting:当我使用以下命令进行绘图时:

sns.set(style="whitegrid")
plt.figure(figsize=(12,10))
sns.lineplot(x= 'date', y='value', hue='TEILNR', ci=None,
                 data=df, lw=1)
plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")

plt.xticks(rotation=45)
plt.show()

I get the following output:我得到以下 output:

在此处输入图像描述

I am confused about the legend, this should respect the values of my TEILNR column or not?我对传说感到困惑,这是否应该尊重我的TEILNR列的值? Why is there not any 351 or 833?为什么没有 351 或 833?

You need to explicitly convert it to categorical:您需要将其显式转换为分类:

DATE = pd.date_range('2020-01-01', periods=8, freq='M')
df = pd.DataFrame({'TEILNR':np.repeat(['351','833'],8),
                  'value':np.random.normal(0,1,16),
                  'date':pd.concat([pd.Series(DATE),pd.Series(DATE)])})

df.dtypes

TEILNR            object
value            float64
date      datetime64[ns]
dtype: object

I plot the two different types side by side, you can see once TEILNR is converted to categorical, the plot is correct, where hue treats it as categorical:我 plot 并排了两种不同的类型,您可以看到一旦将 TEILNR 转换为分类,plot 是正确的,其中色调将其视为分类:

fig, ax = plt.subplots(1,2,figsize = (10,4))
sns.set(style="whitegrid")
sns.lineplot(x= 'date', y='value', hue='TEILNR', ci=None,data=df, lw=1,ax=ax[0])

df['TEILNR'] = df['TEILNR'].astype('category')
sns.lineplot(x= 'date', y='value', hue='TEILNR', ci=None,data=df, lw=1,ax=ax[1])

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM