python - 如何在 Altair 中包裹轴标签

标签 python 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 轴上的第三个标签(即“我不明白这个问题”)被截断。我想将其包裹起来以使整个标签可见。有人可以帮忙吗?非常感谢!

enter image description here

想要的图表是这样的:

enter image description here

最佳答案

您可以使用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'
)

enter image description here

alt.Chart(df).mark_bar().encode(
    x='value',
    y=alt.Y('label', axis=alt.Axis(labelLimit=200))
)

enter image description here


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

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

enter image description here

关于python - 如何在 Altair 中包裹轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71215156/

相关文章:

python - 移动浏览器 Vega-Lite 规范中的间隔选择

python - Django 将日期时间转换为 JSON 可序列化字符串

java - 无法运行星火

python - Altair 更改边框颜色 LayerChart

panel - 牵牛星和面板 : Save as button not showing

python - 在 Altair 中更改图例的大小

python - 如何在 PySide6 中使用 QT6 Dark Theme?

python - 如何使用 pyqrcode 创建 vCard 二维码?

Python Dataframe包含字典列表,需要使用字典项创建新的dataframe

python - 将过滤器变换应用于 Altair 图,同时保留所有图例类别