[Python] How do I make a mark_rule that stops at a previously defined line?

Discussão em 'Python' iniciado por Stack, Agosto 27, 2025.

  1. Stack

    Stack Membro Participativo

    I've plotted a curve which involved some transform calculations, and now I want to place a vertical rule at a specific x location that stops at the height corresponding to that line.

    [​IMG]

    This is what I've managed to do so far, but feels to cumbersome and it does not work entirely either. I'm filtering the value in the x domain that's closest to where I want to place the rule, as follows:

    import numpy as np
    import altair as alt
    import scipy

    np.random.seed(1)
    _data = pl.DataFrame({"x": scipy.stats.norm().rvs(200)})
    _cdf = (
    alt.Chart(_data).mark_area(opacity=0.7)
    .transform_quantile(quantile="x", as_=["prob", "value"])
    .encode(
    alt.X("value:Q"),
    alt.Y("prob:Q"),
    )
    )

    _rule_x = 0
    _rule = _cdf.transform_calculate(
    dist=f"abs(datum.value - {_rule_x})"
    ) .transform_joinaggregate(
    min="min(dist)"
    ).transform_filter(
    "datum.dist <= datum.min"
    ).transform_window(
    rank_dist="rank(datum.dist)",
    frame=[None, None],
    ).transform_filter(
    "datum.rank_dist <= 5"
    ).mark_rule().encode(
    alt.X("value:Q"),
    # alt.XDatum(_rule_x),
    alt.Y("prob:Q")
    )

    _cdf + _rule


    The thing is:

    1. As you can see in the image above, the rule is not exactly at 0, it's at the value in "x" that's closest to 0.
    2. I can force the rule to be at 0 (see the commented line in the code), but then it will not stop at the height of the curve at 0, which is actually a result of interpolation.

    I'd like to be able to place the mark_rule exactly wherever I want, and for it to stop at the height defined by the interpolated curve.

    Also it feels like I'm doing so many transforms for a relatively simple concept, is there a better way to go about it?

    Continue reading...

Compartilhe esta Página