Jump to content

User:0x0077BE/Code/NASA Federal Budget

From Wikipedia, the free encyclopedia

Below is the code to generate the two charts of NASA's federal budget (inset), using Python and matplotlib. The data were taken from Budget of NASA, and are available as a .json file below. If you update the .json file, make sure to adjust the end_year parameter appropriately.

"""
Generate a plot for the NASA data

Licensed under CC-0
"""
from json import load as load_json
import numpy as np
from matplotlib import pyplot as plt

# Load the NASA data
data_loc = 'nasa_budget.json'
save_loc_bar = 'NASA-Budget-Federal.svg'
save_loc_line = 'NASA-Budget-Federal-Line.svg'

make_line = True
make_bar = True

with open(data_loc, 'r') as data_file:
    data_dict = load_json(data_file)

cal_year = np.array(data_dict['year'])
perc_budget = np.array(data_dict['perc_budget'])

# Setup some plot parameters
start_year = 1958
end_year = 2012

plt_title = 'NASA Budget as a Percentage of Federal Budget'
y_lab = 'Percentage of Federal Budget'
x_lab = 'Calendar Year'

bar_color='#cc0e0e'
line_color= '#940000'
grid_color = '#a5a5a5'
cdpi = 150
fsize=(10, 6.5)

if make_bar:
    # Set up the plot
    fig = plt.figure(figsize=fsize, dpi=cdpi)
    ax = plt.axes(axisbg='none')

    # Create a bar chart
    ax.bar(cal_year, perc_budget, color=bar_color, zorder=5)

    ax.grid(color=grid_color, axis='y', linestyle='-', zorder=0)

    plt.xlabel(x_lab, fontweight='bold')
    plt.ylabel(y_lab, fontweight='bold')
    plt.title(plt_title, fontweight='bold')

    ax.set_xlim([start_year, end_year])

    xticks = range(start_year, end_year+1, 3)           # Every third year, 2-digits.
    ax.set_xticks(xticks)
    ax.set_xticklabels(['{:02.0f}'.format(xtick%100) for xtick in xticks])

    plt.tight_layout()

    # Show and save the figure
    plt.show()
    plt.savefig(save_loc_bar, transparent=True, dpi=cdpi)

if make_line:
    # Set up the plot
    fig = plt.figure(figsize=fsize, dpi=cdpi)
    ax = plt.axes(axisbg='none')

    # Create a bar chart
    ax.plot(cal_year, perc_budget, '-', linewidth=2, color=line_color, zorder=5)
    
    ax.grid(color=grid_color, axis='y', linestyle='-', zorder=0)

    plt.xlabel(x_lab, fontweight='bold')
    plt.ylabel(y_lab, fontweight='bold')
    plt.title(plt_title, fontweight='bold')

    ax.set_xlim([start_year, end_year])

    xticks = range(start_year, end_year+1, 3)           # Every third year, 2-digits.
    ax.set_xticks(xticks)
    ax.set_xticklabels(['{:02.0f}'.format(xtick%100) for xtick in xticks])


    plt.tight_layout()

    # Show and save the figure
    plt.show()
    plt.savefig(save_loc_line, transparent=True, dpi=cdpi)