I am trying to determine how to change the default categorical xtick labels in a seaborn box plot. Note that I do not want to change the column names in the data frame.
Here is my code:
import matplotlib
import seaborn as sns
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# Create a sample data frame with categorical labels. Assume we do not want to change the category values in the data frame.
data1 = pd.DataFrame({'value': np.random.randn(1000),'category': 1})
data2 = pd.DataFrame({'value': np.random.randn(1000)+1,'category': 2})
data3 = pd.DataFrame({'value': np.random.randn(1000)+3,'category': 3})
data4 = pd.DataFrame({'value': np.random.randn(1000)+4,'category': 4})
data = pd.concat([data1,data2,data3,data4],axis=0)
# initial plot before adjustments
fig,ax = plt.subplots()
sns.boxplot(data,x='category',y='value',ax=ax)
# the mapping from existing category labels to new ones:
mapping = {'1': 'Dog', '2': 'Cat', '3': "Lizard", '4': "Insect", '5': 'Horse'}
# apply mapping to get new xtick labels for recently created plot.
for x in ax.get_xticklabels():
x.set_text(mapping[x.get_text()])
## tried this too, didn't change anything -> ax.set_xticklabels([mapping[x] for x in ax.get_xticklabels()])
# save result
fig.savefig('myplot.png')
Here is what I get:
I had hoped and expected the plot visualized to have the xtick labels ‘Dog’, ‘Cat’, ‘Lizard’, ‘Insect’ and not the original ‘1’-‘4’. But this is not the case. What I’m doing does not appear to (permanently) change the correct objects. I checked that x.get_text()
is returning ‘1’-‘4’ and this is indeed the case. It appears that x.set_text()
is not saving the new label.
Q: How do I change the labels to get what I want?