Altair: Add an horizontal line to an existent chart

Created on 2 Apr 2020  路  4Comments  路  Source: altair-viz/altair

Hello, I am using chime project to simulate some numbers to a local hospital and I would like to add a line with the maximum hospital capacity that will work as a threshold. For that I need to add a horizontal line, i.e, y=100 to this chart. I am having an hard time doing it, though.

What would be the best approach to do this?

Kind regards

def build_census_chart(
    *,
    alt,
    census_df: pd.DataFrame,
    max_y_axis: Optional[int] = None,
    hospital_maximum_capacity: Optional[int] = None,
) -> Chart:
    """Build census chart."""
    y_scale = alt.Scale()
    if max_y_axis:
        y_scale.domain = (0, max_y_axis)

    x = dict(shorthand="date:T", title="Date", axis=alt.Axis(format=(DATE_FORMAT)))
    y = dict(shorthand="value:Q", title="Census", scale=y_scale)
    color = "key:N"
    tooltip = ["date:T", alt.Tooltip("value:Q", format=".0f", title="Census"), "key:N"]

    # TODO fix the fold to allow any number of dispositions
    points = (
        alt.Chart()
        .transform_fold(fold=["hospitalized", "icu", "ventilated"])
        .encode(x=alt.X(**x), y=alt.Y(**y), color=color, tooltip=tooltip)
        .mark_line(point=True)
    )
    bar = (
        alt.Chart()
        .encode(x=alt.X(**x))
        .transform_filter(alt.datum.day == 0)
        .mark_rule(color="black", opacity=0.35, size=2)
    )
    '''bar = (
        alt.Chart()
        .encode(y=alt.Y(**y))
        .transform_filter(alt.datum.day == 0)
        .mark_rule(color="red", opacity=0.35, size=2)
    )'''

    return alt.layer(points, bar, data=census_df)
question

Most helpful comment

The best way to do this is with a rule mark:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100)
})

chart = alt.Chart(df).mark_point().encode(x='x', y='y')
line = alt.Chart(pd.DataFrame({'y': [1]})).mark_rule().encode(y='y')

chart + line

visualization - 2020-04-02T065631 323

Note that in the next version of Altair (4.2) this will be slightly easier using the datum encoding; the horizontal line will look something like this:

alt.Chart().mark_rule().encode(y=alt.datum(1))

(The final API has not been decided yet)

All 4 comments

The best way to do this is with a rule mark:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100)
})

chart = alt.Chart(df).mark_point().encode(x='x', y='y')
line = alt.Chart(pd.DataFrame({'y': [1]})).mark_rule().encode(y='y')

chart + line

visualization - 2020-04-02T065631 323

Note that in the next version of Altair (4.2) this will be slightly easier using the datum encoding; the horizontal line will look something like this:

alt.Chart().mark_rule().encode(y=alt.datum(1))

(The final API has not been decided yet)

That is perfect, thank you! :)

Is there any way to make the line dashed?

Yes, for example, use

mark_rule(strokeDash=[10, 10])

Hey, how would we add a horizonal line for an interactive scatter plot (with a tooltip)?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

LukeMathWalker picture LukeMathWalker  路  3Comments

dzonimn picture dzonimn  路  3Comments

DentonGentry picture DentonGentry  路  3Comments

morberg picture morberg  路  3Comments

fischcheng picture fischcheng  路  4Comments