简体   繁体   中英

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 (ie "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:

在此处输入图像描述

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM