Skip to content Skip to sidebar Skip to footer

Altair Limit Number Of Bars In Facet Chart

Suppose that I have a pandas dataframe like this one: label counts group 4 4 8 1 5 5 7 1 6 6 6 1 7 7 5 1 0

Solution 1:

You can do this using the same approach as in Altair limit number of bars, but use the groupby argument in the window transform:

import altair as alt
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO("""
   label  counts  group
4      4       8      1
5      5       7      1
6      6       6      1
7      7       5      1
0      0       4      2
1      1       3      2
2      2       2      2
3      3       1      2
"""), delim_whitespace=True)

alt.Chart(df).transform_window(
    rank='rank(counts)',
    sort=[alt.SortField('counts', order='descending')],
    groupby=['group']
).transform_filter(
    alt.datum.rank <= 3
).mark_bar().encode(
    x='counts:Q',
    y='label:O',
    row='group:O'
).resolve_scale(
    y='independent'
)

enter image description here

Post a Comment for "Altair Limit Number Of Bars In Facet Chart"