Nicolaj Spiegelhauer
Nicolaj Spiegelhauer

Reputation: 109

Change labels from data received from database in Altair bar graph

I am trying to edit the labels from the data a have received from a database. As of now I have tried using .transform_fold() but when I run my code the correct titles are appearing but with no data shown on the Graph.

With out the .transform_fold() the graph looks like the following: Graph without transform_fold

And like the following with .transform_fold():

Graph with transform_fold

I would like to have the titles changed like so:

title from data New title
audiobook_processed Audiobooks processed
n_known_errors Known Errors
n_unknown_errors Unknown Errors

The data I receive is like the following:

date value name
2022-01-19 98 audiobook_processed
2022-01-19 69 n_known_errors
2022-01-19 2 n_unknown_errors

My code:

import altair as alt
import streamlit as st
import pandas as pd
import datetime

from xxx.input import get_xxx_metrics

def graph_visual_data():
    data = get_xxx_metrics('audiobook')
    data = data[data.name.isin(['audiobook_processed', 'n_unknown_errors', 'n_known_errors'])][['date','value','name']]

    data.date = data.date.dt.date
    data.value = data.value.astype(int)

    data = data.groupby(['date','name'], as_index=False).sum()

    fig = (alt.Chart(data).transform_fold(
    fold=['Audiobooks processed', 'Known Errors','Unknown Errors'], 
    as_=['name', 'value']).mark_bar(size=15).encode(
        x=alt.X('date:T', axis=alt.Axis(format='%b %-d'), scale=alt.Scale(padding=15), title='Dates processed on'),
        y=alt.Y('value', title='Total amount'),
        color=alt.Color('name', title='Audiobooks processed and errors', sort=['audiobook_processed']),
        tooltip=['name', 'value', 'date']).properties(width=500))
    st.altair_chart(fig)

Upvotes: 1

Views: 381

Answers (1)

jakevdp
jakevdp

Reputation: 86443

You could do this by replacing the values within the pandas dataframe before building the chart:

data['name'] = data['name'].replace({
    'audiobook_processed': 'Audiobook processed',
    'n_unknown_errors': 'Unknown Errors',
    'n_known_errors': 'Known Errors',
})

and then skip transform_fold, because it does not apply here.

Upvotes: 1

Related Questions