Issue
For some reason, when I try to use a matplotlib.ticker.FuncFormatter to reformat the x axis of a seaborn stripplot, it reformats the positions instead of the labels, MWE below. Using the same formatter function on a normal matplotlib scatterplot works fine, and gives the expected result.
There's also something else I don't understand about how the labels work, because printing one from each axis shows the same thing for the default and reformatted stripplots, which does not match the figure, and then gives an empty string for the scatterplot label...
original stripplot label: Text(3, 0, '0.3')
reformatted stripplot label: Text(3, 0, '0.3')
reformatted scatterplot label: Text(0, 0, '')
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'x': np.random.randint(0,10,size=100) / 10, 'y': np.random.normal(size=100)})
fig, axarr = plt.subplots(3,1)
sns.stripplot(data=df, x='x', y='y', ax=axarr[0])
axarr[0].set_title('stripplot, default formatting')
print(f' original stripplot label: {axarr[0].get_xticklabels()[3]}')
sns.stripplot(data=df, x='x', y='y', ax=axarr[1])
axarr[1].xaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: f'{x:.2f}'))
axarr[1].set_title('stripplot, incorrect formatting')
print(f' reformatted stripplot label: {axarr[1].get_xticklabels()[3]}')
axarr[2].scatter(df.x, df.y, s=10, alpha=0.5)
axarr[2].xaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: f'{x:.2f}'))
axarr[2].set_title('scatterplot, correct formatting')
print(f' reformatted scatterplot label: {axarr[2].get_xticklabels()[3]}')
fig.tight_layout()
Solution
You want to use native_scale=True
to preserve the number-ness of the data on the x axis:
sns.stripplot(data=df, x='x', y='y', native_scale=True, ax=axarr[1])
This feature is new in 0.12.0 for strip/swarmplot, and new in 0.13.0 for other categorical functions.
Answered By - mwaskom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.