如何在 Altair 中包装轴标签

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

目前(见下面的输出),y 轴上的第三个标签(即“我不明白这个问题”)被截断了。我想把它包起来,让整个标签可见。任何人都可以帮忙吗?非常感谢!

想要的图表是这样的:

您可以使用labelLimit来控制标签何时被截断:

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))
)


您也可以通过创建列表来换行,如评论中所建议:

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)),
)