seabornのhueでカテゴリ変数表示がうまくいかない場合
ダミーデータ生成
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt #データ生成 lot = [i for i in range(1000, 1010)] number = list(range(1, 10)) lot_number = pd.DataFrame([(l, n) for l in lot for n in number], columns=['Lot', 'No']) xydata = pd.DataFrame(np.random.randn(len(lot_number),2), columns=['X', 'Y']) df = pd.concat([lot_number, xydata], axis=1) print(df) # Lot No X Y #0 1000 1 0.346488 -0.397770 #1 1000 2 0.912600 1.348908 #2 1000 3 -0.747714 -1.843285 #3 1000 4 1.227155 1.134689 #4 1000 5 0.215866 0.732671 #.. ... .. ... ... #85 1009 5 0.790056 -0.754990 #86 1009 6 -0.078101 0.172408 #87 1009 7 -0.559847 1.270743 #88 1009 8 0.035741 1.466583 #89 1009 9 1.826485 0.079415 # #[90 rows x 4 columns]
普通に表示
sns.scatterplot(data=df, x='X', y='Y', hue='Lot') plt.show()
解決策
いやそうじゃないんや。ってなってLotをstr指定してみる。
print(df.dtypes) #Out[32]: #Lot int64 #No int64 #X float64 #Y float64 #dtype: object df['Lot'] = df['Lot'].astype('str') print(df.dtypes) #Lot object #No int64 #X float64 #Y float64 #dtype: object sns.scatterplot(data=df, x='X', y='Y', hue='Lot') plt.show()
これで大抵できるが、たまにできないのでその場合はastype('str')
の代わりにastype('category')
を使う。