Cat codes not working properly in Matplotlib

Viewed 39

I am working on a small dataset given as;

temp2 = pd.DataFrame({'bmi':[36.5,28.1,29.0,12.3], 'glucose':[55,123,234,123.6],'stroke':[1,1,0,1]})
temp2[['bmi','glucose']]=temp2[['bmi','glucose']].astype('float32')
temp2['stroke']=temp2['stroke'].astype('category')
temp2.dtypes

bmi        float32 
glucose    float32 
 stroke     category
  dtype: object

The goal is to draw a scatterplot and coloring based on stroke variable. Here is my attempt;

fig, ax = plt.subplots(figsize=(10,8))
 ax.scatter(x= temp2['glucose'], y=temp2['bmi'], c=temp2['stroke'].cat.codes,\
      marker= 'o', s=50, vmax=len(temp2['stroke'].unique()))
 #plt.gray()
 ax.set_xlabel('Glucose level')
 ax.set_ylabel('BMI')
 ax.set_title('BMI vs. Glucose Level for Patients')
 plt.show()

But I am getting only one type of color, plz see screenshot;

enter image description here Matplotlib version 3.3.2, python 3.8.6, pandas 1.1.4 Help is appreciated.

1 Answers

I am sure there are better answers available, but an alternative way I found is this;

fig, ax = plt.subplots(figsize=(10,8))
colormap = np.array(['r', 'g'])
ax.scatter(x= temp2['glucose'], y=temp2['bmi'], c=colormap[temp2['stroke'].cat.codes,
      marker= 'o', s=50)

ax.set_xlabel('Glucose level')
ax.set_ylabel('BMI')
ax.set_title('BMI vs. Glucose Level for Patients')
plt.show()

This gives me the desired output;

enter image description here

Thanks for responding to my question. Highly appreciated

Related