Sowji Ch
Sowji Ch

Reputation: 25

How to label categorical variable in barplot?

I developed a barplot for some data using python.How do you develop labels for the categorical values?

The data represents 0="Female" and 1="Male". The barplot developed shows only 0 and 1 but I want to represent as Female and Male.

Using the following code I got the below output:

sns.barplot(x=df.cp, y=df.chol, hue=df.sex, palette='spring')
plt.xlabel("Chest Pain Type")
plt.ylabel("Serum Cholesterol")
plt.show()

Output

I tried adding this piece of code to the above but the output is not as expected and color differentiation is missing:

plt.legend(title="sex", loc="upper right", labels=["Female", "Male"])

Output

Thank you

Upvotes: 0

Views: 989

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339520

The idea of seaborn is mostly that you can directly use the columns of a dataframe. So the easiest solution to get the correct labels is to have those labels in the data you supply to the dataframe. E.g. having a dictionary that maps numbers to names

{1 : "male", 0 : "female"}

you can replace the data in the respective column before plotting:

sns.barplot(x="cp", y="chol", hue="sex", palette='spring', 
            data=df.replace({"sex" : {1 : "male", 0 : "female"}}))

Upvotes: 1

Related Questions