altair-tutorial
altair-tutorial copied to clipboard
pct parameter in transform_calculate
I'm trying to adapt the code from the following post: https://stackoverflow.com/questions/56358977/how-to-show-a-histogram-of-percentages-instead-of-counts-using-altair.
I looked through the documentation for the transform_calculate to find an explanation of the pct parameter but the search came up empty. Is it possible to update the documentation?
Alternatively, is there a different/better way to plot a histogram of percentages instead of counts using Altair?
Copying the code in question:
import pandas as pd
import altair as alt
source = pd.DataFrame({'age': ['12', '32', '43', '54', '32', '32', '12']})
alt.Chart(source).transform_joinaggregate(
total='count(*)'
).transform_calculate(
pct='1 / datum.total'
).mark_bar().encode(
alt.X('age:Q', bin=True),
alt.Y('sum(pct):Q', axis=alt.Axis(format='%'))
)
pct here is the name of the new field that holds the result of the calculation, later used in the encoding. You can replace that name with whatever name you want.
is there a different/better way to plot a histogram of percentages instead of counts using Altair?
No, that answer shows the best way to plot a histogram of percentages.
Thank you for your prompt response!
Is the creation of new fields that can be used as an encoding documented somewhere in the user guide?
Yes, see the examples at https://altair-viz.github.io/user_guide/transform/calculate.html