altair-tutorial icon indicating copy to clipboard operation
altair-tutorial copied to clipboard

pct parameter in transform_calculate

Open ykharitonova opened this issue 5 years ago • 3 comments

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?

ykharitonova avatar Apr 29 '20 19:04 ykharitonova

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.

jakevdp avatar Apr 29 '20 22:04 jakevdp

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?

ykharitonova avatar Apr 30 '20 03:04 ykharitonova

Yes, see the examples at https://altair-viz.github.io/user_guide/transform/calculate.html

jakevdp avatar Apr 30 '20 05:04 jakevdp