简体   繁体   中英

Altair interactive chart: Show all axis labels while transform_filter only takes part of the data

See example below. What I would like to happen is that the barchart (on right) always shows all xlabels (A to Z), regardless of whether they exist in the selection (in left chart). I find a lot of information online about formatting labels, but not about setting them. Can I manually set the xlabels somehow, or use the not-filtered data as a base for the xlabels?

import altair as alt
import pandas as pd
import random
import string

random.seed(42)

consultation_dates = pd.date_range(start='1/1/2018', end='1/08/2020')
disease_codes = random.choices(string.ascii_uppercase, k=len(consultation_dates))
consultation_weights = [random.randint(1, 4) for i in range(len(consultation_dates))]

df = pd.DataFrame({'date': consultation_dates,
                  'disease_code': disease_codes,
                  'consultation_weight': consultation_weights})

selected_range = alt.selection_interval(encodings=['x'])

use_over_time = alt.Chart(df).mark_area().encode(
    x='yearquarter(date):Q',
    y='sum(consultation_weight):Q'
).add_selection(
    selected_range
)

use_by_disease = alt.Chart(df).mark_bar().encode(
    x='disease_code:N',
    y='sum(consultation_weight):Q'
).transform_filter(
    selected_range
)

use_over_time | use_by_disease

Found my own answer. It can be done with layering!

import altair as alt
import pandas as pd
import random
import string

random.seed(42)

consultation_dates = pd.date_range(start='1/1/2018', end='1/08/2020')
disease_codes = random.choices(string.ascii_uppercase, k=len(consultation_dates))
consultation_weights = [random.randint(1, 4) for i in range(len(consultation_dates))]

df = pd.DataFrame({'date': consultation_dates,
                  'disease_code': disease_codes,
                  'consultation_weight': consultation_weights})

selected_range = alt.selection_interval(encodings=['x'])

use_over_time = alt.Chart(df).mark_area().encode(
    x='yearquarter(date):Q',
    y='sum(consultation_weight):Q'
).add_selection(
    selected_range
)


use_by_disease_base = alt.Chart(df).mark_bar(opacity=0.3).encode(
    x='disease_code:N',
    y='sum(consultation_weight):Q',
    color=alt.value('lightgray')
)
use_by_disease = alt.Chart(df).mark_bar(opacity=0.3).encode(
    x='disease_code:N',
    y='sum(consultation_weight):Q'
).transform_filter(
    selected_range
)

use_over_time | (use_by_disease_base + use_by_disease)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM