I'm trying to create bar plot with labels on bars. Position of labels and color of labels depends on column of dataframe. Also, I would like to color bars by column.
My data:
data = {
'Survived': ['0', '1'],
'count': [500, 100],
'label_position': ['R', 'L']
}
df = pd.DataFrame(data)
I tried to create following plot:
import seaborn.objects as so
p = (
so.Plot(df, x='count', y='Survived')
.add(so.Bar(alpha=1), color='Survived')
.add(
so.Text({"fontweight": "bold"}),
text='count',
halign='label_position',
color="label_position"
)
.scale(
halign={'L':'left', 'R':'right'},
color={'L':'black', 'R':'white'}
)
)
p.plot()
but this code raises following error:
PlotSpecError: Scale setup failed for the `color` variable. See the traceback above for more information.
because both visualizations have attribute color.
I'm able co color bars, or the text, but not both at once.
Colored bars: color the bars
Colored text: color the text
Is there any posibility to color both?
If we see the traceback above for more information
as the exception message suggests, it says
ValueError: No entry in color dictionary for '0', '1'
So we could try adding entries for those keys:
(
so.Plot(df, x='count', y='Survived')
.add(so.Bar(alpha=1), color='Survived')
.add(
so.Text({"fontweight": "bold"}),
text='count',
halign='label_position',
color="label_position",
)
.scale(
halign={'L':'left', 'R':'right'},
color={'L':'black', 'R':'white', '0': 'black', '1': 'white'}, # <-----
)
)
That works but now we have some entries in the legend that we probably don't want. There's not in general a way to control what shows up in the legend independently of what actually gets mapped for Nominal
scales, but for this particular plot the color encoding is redundant anyway so we don't actually need the legend:
(
so.Plot(df, x='count', y='Survived')
.add(so.Bar(alpha=1), color='Survived', legend=False) # <-----
.add(
so.Text({"fontweight": "bold"}),
text='count',
halign='label_position',
color="label_position",
)
.scale(
halign={'L':'left', 'R':'right'},
color={'L':'black', 'R':'white', '0': 'black', '1': 'white'},
)
)