2
votes

I'm using seaborn to make nice categorical plots. seaborn.catplot helps me a lot. It uses column names of pandas.DataFrame as labels, however sometimes I want to rename these labels on my plots.

It's pretty obvious that I can use matplotlib.pyplot to set axes labels, titles and so on. But how can I change hue label? I don't want ugly_column_name to display on my plot. I want a different string, may it be Pretty Category for instance.

Here is extremely simplified code of my plot, and the resulting image. How do I edit hue label here? Is there a simple one-liner?

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({"ugly_column_name": ["foo", "foo", "foo", "bar", "bar", "bar"],
                     "x": [1, 2, 3, 1, 2, 3],
                     "y": [1, 1.1, 1.5, 1.1, 1.5, 2.0]}
                    )
sns.catplot(x="x", y="y", data=data, hue="ugly_column_name")
plt.xlabel('More than just lowerscore x')

catplot sample

1
This is not a best way to solve the issue. Label can be long, it can contain special characters and so on. I still need to use the dataframe after plots, and I don't want to type long label as column name.Dmitrii Begal

1 Answers

0
votes

You can use Dataframe.replace

In your case, add this line(s) to your code:

data = data.replace(to_replace="foo", value="foo_alternative")

Pleae check the snippet:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({"ugly_column_name": ["foo", "foo", "foo", "bar", "bar", "bar"],
                     "x": [1, 2, 3, 1, 2, 3],
                     "y": [1, 1.1, 1.5, 1.1, 1.5, 2.0]}
                    )

data = data.replace(to_replace="foo", value="foo_alternative")
data = data.replace(to_replace="bar", value="bar_alternative")

sns.catplot(x="x", y="y", data=data, hue="ugly_column_name")
plt.xlabel('More than just lowerscore x')