# for data wrangling
import pandas as pd
# for pulling FRED data
import pandas_datareader as pdr
# for visualization
import altair as alt
National Debt
The Wall Street Journal recently ran an excellent article on the U.S. federal debt, you can check it here though it is behind their paywall.
In this blog post we show how to replicate the main charts using Python
and freely available data from FRED. But beware, seeing these charts will leave you somewhat depressed about the current state of our public finances.
First step, import libraries.
Figure 3: Total spending on Defense and Interest Payments
Our last chart compares the time series of nominal dollars spent on National Defense versus the spending on servicing the debt itself, namely the interest payments. Both items come from FRED, the mnemonic for defense expenditures is FDEFX and the one for interest payments is A091RC1Q027SBEA.
Note that we make our dataframe long (also sometimes called tidy or stacked), this type of long data is more convenient for performing operations and creating charts.
= (
def_exp # pull data from FRED
'FDEFX', 'A091RC1Q027SBEA'],
pdr.get_data_fred([='1980-01-01')
start# go from billions to trillions
= lambda df: df['FDEFX']/1000,
.assign(Defense = lambda df: df['A091RC1Q027SBEA']/1000)
Interest # pull out index as column
.reset_index()# make data long
='DATE',
.melt(id_vars=['Defense','Interest'])
value_vars )
Now we make a the chart. Notice that we create our own label for the y-axis so we can make clear the data is in trillions of dollars. In addition, we name a color encoding which is what actually separates the series and assigns them different colors.
# main layer
= (
def_plot
alt.Chart(def_exp,='Government spending on interest versus defense')
title
.mark_line()
.encode('DATE:T').title(None),
alt.X('value:Q').title(None)
alt.Y(='"$" + datum.value + "T"'),
.axis(labelExpr'variable:N').legend(None)
alt.Color(=['Defense','Interest'],
.scale(domainrange=['olive','darkred'])
)
)
# labels for series
= (
labels 'DATE=="2020-01-01"'))
alt.Chart(def_exp.query(=-30, dx=-10,
.mark_text(dy=16)
fontSize
.encode('DATE:T'),
alt.X('value:Q'),
alt.Y('variable:N'),
alt.Color('variable:N')
alt.Text(
)
)
# all together
alt.layer(def_plot, labels, footer)
Did we mention that these charts are a bit depressing? We are now paying more to service the debt than in national defense.