'How to wrap axis label in Altair
bars = alt.Chart(df).mark_bar().encode(
x=alt.X('Pcnt:Q', axis=None),
y=alt.Y('Name',
axis=alt.Axis(domain=False,
ticks=False,
title=None,
labelPadding=15,
labelFontSize=16,
labelColor='#404040',
labelBaseline='middle',
# labelAngle= -45,
# labelExpr=axis_labels
),
sort=name_sort
)
)
text = bars.mark_text(align='left', baseline='middle', dx=3, size=14).\
encode(text=alt.Text('Pcnt:Q',format='.0%'))
Votes = (bars+text).properties(width=500,height=100
).properties(title={
"text": ["Who Shot First?"],
"subtitle": ["According to 834 respondents"],
"fontSize": 26, "color": '#353535',
"subtitleFontSize": 20, "subtitleColor": '#353535',
"anchor": 'start'}
).configure_mark(color='#008fd5'
).configure_view(strokeWidth=0
).configure_scale(bandPaddingInner=0.2
)
Votes
Currently (see below output), the third label in y-axis (i.e. "I don't understand this question") got truncated. I want to wrap it to make the whole label visible. Anyone can help? Thank you very much!
Desired chart is like this:
Solution 1:[1]
You can use labelLimit
to control when the label is truncated:
import pandas as pd
import altair as alt
df = pd.DataFrame({
'label': ['Really long label here that will be truncated', 'Short label'],
'value': [4, 5]
})
alt.Chart(df).mark_bar().encode(
x='value',
y='label'
)
alt.Chart(df).mark_bar().encode(
x='value',
y=alt.Y('label', axis=alt.Axis(labelLimit=200))
)
You can also wrap on multiple lines by creating a list, as suggested in the comments:
from textwrap import wrap
# Wrap on whitespace with a max line length of 30 chars
df['label'] = df['label'].apply(wrap, args=[30])
alt.Chart(df).mark_bar().encode(
x='value',
y=alt.Y('label', axis=alt.Axis(labelFontSize=9)),
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | joelostblom |