Seaborn: Too many decimal places in legend labs for relplot with hue or size keywords

Created on 22 Mar 2019  路  5Comments  路  Source: mwaskom/seaborn

I ran into this problem with a particular dataset. Calling replot with either hue or size causes extremely long labels in the legend because of what looks like floating point arithmetic in the labeling logic.

Example:

test = pd.DataFrame({
 'foo' :[1,2,3,4,5,6,7],
 'bar' :[4,6,8,3,5,4,6],
    'baz':[0.4, 0.19, 0.35, 0.22, 0.35, 0.31, 0.09]
}
)
sns.relplot(
data=test.head(7),
x='foo',
y='bar',
size='baz')

Selection_006

Is there some way that the legend labels could be rounded or otherwise formatted to prevent this?

Most helpful comment

Workaround for anyone else who finds themselves looking at this:

plot =sns.relplot(
data=test.head(7),
x='foo',
y='bar',
size='baz')

leg = plot._legend
for t in leg.texts:
    # truncate label text to 4 characters
    t.set_text(t.get_text()[:4])

All 5 comments

Glancing at other recent issues, I think this is related to https://github.com/mwaskom/seaborn/issues/1653

Workaround for anyone else who finds themselves looking at this:

plot =sns.relplot(
data=test.head(7),
x='foo',
y='bar',
size='baz')

leg = plot._legend
for t in leg.texts:
    # truncate label text to 4 characters
    t.set_text(t.get_text()[:4])

same problem found on scatterplot
`test = pd.DataFrame({
'foo': [1,1,1,1,1,
2,2,2,2,2,
3,3,3,3,3,],
'bar': ['A', 'B', 'C', 'D', 'E'] * 3,
'baz': [
1.113724, 1.684478, 1.258712, 1.093084, 2.043681,
1.373130, 1.486539, 1.325999, 1.428729, 1.688664,
1.325381, 1.345571, 1.304717, 1.366071, 1.454929]
})

ax = sns.scatterplot(
x='foo',
y='bar',
size='baz',
hue='baz',
palette="YlOrRd",
legend='brief',
data=test)
ax.legend(loc='lower left',
bbox_to_anchor=(1, 0),
ncol=1)`
Screen Shot 2019-12-17 at 3 28 57 PM

python: 3.7.3
pandas: 0.25.3
matplotlib: 3.1.0
seaborn: 0.9.0

Problem still exists. Issue with the truncation fix as above is it shifts the legend rightward

Screen Shot 2020-01-20 at 11 12 32 AM

The specific example at the beginning of this thread now produces the expected result, so if you are having a problem in some other context, you need to provide a reproducible example that demonstrates it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TDaltonC picture TDaltonC  路  3Comments

amelio-vazquez-reina picture amelio-vazquez-reina  路  3Comments

stonebig picture stonebig  路  4Comments

amelio-vazquez-reina picture amelio-vazquez-reina  路  4Comments

sungshine picture sungshine  路  3Comments