Vladimir Vargas
Vladimir Vargas

Reputation: 1834

Altair limit number of bars

Suppose that I have a dataframe like this one

   label  counts
4      4       8
5      5       7
6      6       6
7      7       5
0      0       4
1      1       3
2      2       2
3      3       1

I want to make a bar chart with altair, where the height of the bars is counts, and the label is the label. How do I limit the number of bars to be shown, if I want the top 3 counts?

I know I can make df.sort_values("counts", ascending=False).iloc[:3] to be the source of the chart, but I was wondering if there is a way of doing this directly with altair.

Upvotes: 2

Views: 1154

Answers (1)

jakevdp
jakevdp

Reputation: 86443

You can do this following the Top K Items example from the Altair documentation. Here it is applied to your data:

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

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

enter image description here

Upvotes: 1

Related Questions