To upload files, please first save the app
import streamlit as st
import pandas as pd
import requests
import matplotlib.pyplot as plt
@st.cache_data
def fetch_energy_data():
url = "https://api.eia.gov/v2/seds/data/"
params = {
"frequency": "annual",
"data[0]": "value",
"facets[seriesId][]": ["BMTCB", "CLTCB", "PATCB", "PPTCB", "RETCB"],
"facets[stateId][]": ["US"],
"sort[0][column]": "period",
"sort[0][direction]": "desc",
"offset": 0,
"length": 5000,
"api_key": "XQ6sIdWdcbX3opHOGhFf6mDCyccPkmQ8MZrDwm52"
}
response = requests.get(url, params=params)
if response.status_code == 200:
return pd.DataFrame(response.json()["response"]["data"])
else:
st.error(f"Failed to fetch data. Status code: {response.status_code}")
return pd.DataFrame()
@st.cache_data
def process_energy_data(data):
if data.empty:
return data
data["period"] = data["period"].astype(int)
data["value"] = pd.to_numeric(data["value"], errors="coerce")
category_map = {
"Biomass total consumption": "Biomass",
"Coal total consumption": "Coal",
"All petroleum products total consumption": "Petroleum",
"Natural gasoline (pentanes plus) total consumption": "Natural Gas",
"Renewable energy total consumption": "Renewable Energy"
}
data["category"] = data["seriesDescription"].map(category_map)
category_order = ["Biomass", "Coal", "Petroleum", "Natural Gas", "Renewable Energy"]
data["category"] = pd.Categorical(data["category"], categories=category_order, ordered=True)
return data
def main():
st.title("U.S. Annual Energy Consumption by Category")
st.write("Explore biomass, coal, petroleum, natural gas, and renewable energy consumption by year.")
raw_data = fetch_energy_data()
if raw_data.empty:
st.write("No data available.")
return
processed_data = process_energy_data(raw_data)
st.sidebar.header("Filter Options")
energy_type = st.sidebar.selectbox(
"Select Energy Type:",
["All"] + list(processed_data["category"].cat.categories)
)
if energy_type == "All":
year = st.sidebar.selectbox(
"Select a Year:",
sorted(processed_data["period"].unique(), reverse=True)
)
filtered_data = processed_data[processed_data["period"] == year]
if not filtered_data.empty:
st.subheader(f"All Energy Consumption Categories for {year}")
fig, ax = plt.subplots(figsize=(10, 6))
filtered_data = filtered_data.sort_values(by="category")
filtered_data.set_index("category")["value"].plot(kind="bar", ax=ax)
ax.set_title(f"All Energy Consumption Categories in {year}")
ax.set_ylabel("Energy Consumption (Billion Btu)")
ax.set_xlabel("Category")
plt.xticks(rotation=45, ha="right")
st.pyplot(fig)
else:
st.write(f"No data available for {year}.")
else:
min_year, max_year = st.sidebar.select_slider(
"Select Year Range:",
options=sorted(processed_data["period"].unique()),
value=(processed_data["period"].min(), processed_data["period"].max())
)
filtered_data = processed_data[
(processed_data["category"] == energy_type) &
(processed_data["period"] >= min_year) & (processed_data["period"] <= max_year)
]
if not filtered_data.empty:
st.subheader(f"{energy_type} Consumption from {min_year} to {max_year}")
fig, ax = plt.subplots(figsize=(10, 6))
filtered_data.plot(x="period", y="value", kind="line", marker="o", ax=ax)
ax.set_title(f"{energy_type} Consumption from {min_year} to {max_year}")
ax.set_ylabel("Energy Consumption (Billion Btu)")
ax.set_xlabel("Year")
plt.xticks(rotation=45, ha="right")
st.pyplot(fig)
else:
st.write(f"No data available for {energy_type} from {min_year} to {max_year}.")
st.markdown("***")
st.markdown("**Data Source**: U.S. Energy Information Administration (EIA).")
if __name__ == "__main__":
main()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?