Search code examples
pythonaltair

How to round numbers in Altair


I have a graph that instead of using count() as Y axis I used percentage. I would like to show only the round number and see the whole number 39%, 24%, 37%.

activities = pd.DataFrame({'Activity': ['Sleeping','Sleeping', 'Eating', 'TV', 'Work', 'Exercise'],
                           'Time': [8, 2, 4, 8, 2,2]})

bars =alt.Chart(activities).transform_joinaggregate(
    total='count(*)'
).transform_calculate(
    pct='1 / datum.total'
).mark_bar().encode(
    alt.X('Activity'),
    alt.Y('sum(pct):Q', axis=alt.Axis(format='%'))
)

text = bars.mark_text(
align='right',
baseline='middle',
dx=3, # Nudges text to right so it doesn't appear on top of the bar
dy=-4
).encode(
text='sum(pct):Q'
)
#Change size of graph
Qs2 = (bars + text).properties(
width=800,
height=300,
title=plot_title4
).configure_axis(
labelFontSize=20,
titleFontSize=20,
)
Qs2[enter image description here][1]

Current Graph Desired Graph


Solution

  • I figured it out!

    add Afer = alt.Y(.....) alt.Tooltip(['sum(pct):Q'],format=',.0f', title="Days to respond to a tender")

    and add after mark_text: encode( text=alt.Text("sum(pct):Q", format=",.0f")

    bars =alt.Chart(r).transform_joinaggregate(
        total='count(*)'
    ).transform_calculate(
        pct='100 / datum.total'
    ).mark_bar().encode(
        alt.X('sum(pct):Q'),
        alt.Y('shot_first'),
        alt.Tooltip(['sum(pct):Q'],format=',.2f', title="Days to respond to a tender")
    )
    
    text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3, # Nudges text to right so it doesn't appear on top of the bar
    dy=-4
    ).encode(
            text=alt.Text("sum(pct):Q", format=",.0f", "%")
    )
    
    
    #Change size of graph
    Qs2 = (bars + text).properties(
    width=800,
    height=300,
    title=plot_title4
    ).configure_axis(
    labelFontSize=25,
    titleFontSize=25,
    )
    Qs2