A draft whose bar chart adds up every week
Code review · Medium · §11.4 Checking numbers and diagnosing errors
This is an AI draft of an app that shows the weekly amount (kg) of recycling collected for each item. When you choose only weeks 2 to 4, the metric shows the amount for those weeks, but the bar chart of totals by item still shows the totals for all of weeks 1 to 6.
Change one line so that the metric and the bars show the same range. Grading runs the app again with different items, weeks, and amounts.
Code to fix
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
recycle = pd.DataFrame({
"week": [1, 2, 3, 4, 5, 6] * 3,
"item": ["Paper"] * 6 + ["Plastic"] * 6 + ["Glass"] * 6,
"kg": [52, 48, 61, 55, 58, 63, 31, 35, 29, 40, 38, 36, 20, 18, 25, 22, 19, 24],
})
st.title("Recycling")
items = st.sidebar.multiselect("Item", ["Paper", "Plastic", "Glass"], default=["Paper", "Plastic", "Glass"])
weeks = st.sidebar.slider("Week", 1, 6, (1, 6))
view = recycle[recycle["item"].isin(items) & recycle["week"].between(weeks[0], weeks[1])]
if view.empty:
st.warning("Pick at least one item.")
st.stop()
st.metric("Collected", f"{view['kg'].sum():,} kg")
totals = recycle.groupby("item", as_index=False)["kg"].sum()
fig, ax = plt.subplots(figsize=(4, 3))
ax.bar(totals["item"], totals["kg"])
ax.set(title="Collected by item", ylabel="kg")
st.pyplot(fig)Solve this problem in your browser
Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.