Francisco
Francisco

Reputation: 503

altair pandas value counts horizontal bar chart

import random
random.seed(49)
source = pd.Series([random.choice('abc') for _ in range(100)]).value_counts()
source.plot(kind='barh')

Considering the Value counts series applied above and plot of horizontal bar char with counts of each value occurrence.

How does one replicate this simple example in altair?

Is there a transform avaliable where when can count or group the occurrences of a series then plot avoiding the value_counts method?

pandas 0.25.0 python 3.7

Thanks in advance

Upvotes: 3

Views: 3218

Answers (1)

cast42
cast42

Reputation: 2099

import altair as alt
import random
random.seed(49)
source = pd.Series([random.choice('abc') for _ in range(100)]).value_counts()

alt.Chart(source.reset_index().rename(columns={0:'counts'})).mark_bar().encode(
    y='index:N',
    x='counts'
)

enter image description here

or alternatively let Altair do the counting:

source = pd.DataFrame([random.choice('abc') for _ in range(100)], columns=['kind'])
alt.Chart(source).mark_bar().encode(
    alt.Y('kind:N'),
    alt.X('count(kind):Q')
)

enter image description here

Upvotes: 6

Related Questions