Search code examples
altairfootnotes

Adding footnotes to layered chart in Altair


I am making a layered chart using data from the Bureau of Labor Statistics, and since I am publishing the chart, I need to cite the data source. I need to add a line at the bottom of the chart saying "Source: Bureau of Labor Statistics. Data as of July 2022." I am able to add the title and subtitle, but there doesn't seem to be an option for footnote/source line. Are there any workarounds?

import pandas as pd
import pandas_datareader.data as pdr
import datetime
import altair as alt

start = datetime.datetime (2020, 1, 1)
end = datetime.datetime (2022, 7, 10)

df = pdr.DataReader('UNRATE', 'fred', start, end)
df = df.rename(columns={'UNRATE':'Unemployment Rate'})
df["Date"] = df.index
df['Prepandemic Rate'] = 3.5

source = df

line = (
    alt.Chart(source)
    .mark_line(point=False, strokeWidth=2, color='blue')
    .encode(x="Date", y="Unemployment Rate")
)

line2 = (
    alt.Chart(source)
    .mark_line(point=False, strokeWidth=2, color='red')
    .encode(x="Date", y="Prepandemic Rate")
)

alt.layer(line, line2).properties(
    width=300, height=300, title={
    "text":'Unemployment Rate',
    "subtitle":['Seasonally adjusted']
    },
).configure_title(
  anchor= 'start'
)

Note: I saw this question (How to add a Text Footer to an Altair graph?) but I can't seem to get the concat function to work on my layered chart.


Solution

  • the footer to the faceted chart you can add as a TitleParams to your final chart. You still need to play with font sizes and balance the chart to your liking).

    As for your further request - I updated the code to fit all (title, subtitle, footer), i used @jakevdp idea from this post

    I think this approach makes it easier -> to create Title + subtle as separate charts, add footer inside your original chart, and concatenate all of them.

    You still need to work on alignment, position of your legend, fonts, etc.

    P.S. Or as an alternative approach - use title parameters for title & subtitle, and concatenate footnote.

    df = pd.DataFrame([['Action', 5, 'F'], 
                       ['Crime', 10, 'F'], 
                       ['Action', 3, 'M'], 
                       ['Crime', 9, 'M']], 
                      columns=['Genre', 'Rating', 'Gender'])
    
    chart = alt.Chart(df).mark_bar().encode(
       column=alt.Column(
           'Genre', title=""),
       x=alt.X('Gender', axis=alt.Axis(ticks=False, labels=False, title='')),
       y=alt.Y('Rating', axis=alt.Axis(grid=False)),
       color='Gender'
    
    ).properties(width=100, title=alt.TitleParams(
            ['This is a footer.'],
            baseline='bottom',
            orient='bottom',
            anchor='start',
            fontWeight='normal',
            fontSize=10,
            dy=20, dx=20
        ))
    
    
    
    
    title = alt.Chart(
        {"values": [{"text": "The Title"}]}
    ).mark_text(size=20).encode(
        text="text:N"
    )
    
    subtitle = alt.Chart(
        {"values": [{"text": "Subtitle"}]}
    ).mark_text(size=14).encode(
        text="text:N"
    )
    
    
    
    alt.vconcat(
        title,
        subtitle,
        chart
    ).configure_view(
        stroke=None
    ).configure_concat(
        spacing=1)
    

    updated chart