Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import streamlit as stimport pandas as pdimport altair as altimport plotly.express as pxst.set_page_config(page_title="IL Crop Rotation Explorer", layout="wide")st.title("🌾 Illinois Crop Rotation and Land Use Exploration")st.markdown("Explore dominant crops and land use characteristics across Illinois fields from 2010–2020. This dashboard is for exploration and pattern recognition. Dashboard created by Sara Kiel.")# Load data@st.cache_datadef load_data():return pd.read_csv("crop_final_df.csv")df = load_data()# ---- Sidebar filters ----crop_options = sorted(df['crop_name'].dropna().unique())genlu_options = sorted(df['GenLU'].dropna().unique())selected_crops = st.sidebar.multiselect("Filter by Crop", options=crop_options, default=crop_options[:5])selected_genlu = st.sidebar.multiselect("Filter by General Land Use",options=genlu_options,default=genlu_options[:5])filtered = df[df['crop_name'].isin(selected_crops) &df['GenLU'].isin(selected_genlu)]# ---- Area chart: Crop coverage over time ----coverage = filtered.groupby(['year', 'crop_name'])['pct_crop'].sum().reset_index()area_chart = alt.Chart(coverage).mark_area(opacity=0.7).encode(x=alt.X('year:O', title='Year'),y=alt.Y('pct_crop:Q', title='Total Crop Coverage (%)'),color=alt.Color('crop_name:N', title='Crop'),tooltip=['year', 'crop_name', 'pct_crop']).properties(width=800,height=400,title='Crop Coverage Over Time')# ---- Scatter Plot: Crop Coverage vs Rotation Diversity ----scatter = alt.Chart(filtered).mark_circle(size=60).encode(x=alt.X('year:O', title='Year'),y=alt.Y('rotation_diversity:Q', title='Rotation Diversity'),color=alt.Color('crop_name:N', title='Crop'),size=alt.Size('pct_crop:Q', title='% Crop Coverage'),tooltip=['crop_name', 'year', 'pct_crop', 'rotation_diversity', 'GenLU']).properties(width=800,height=400,title='Crop Coverage vs. Rotation Diversity Over Time')# -- Prepare continuous corn data --df['cc_years'] = df['CCCount'].str.extract(r'(\d+):').astype(float)# -- Bar chart: Frequency of Continuous Corn Planting --cc_bar = alt.Chart(df).mark_bar().encode(x=alt.X('cc_years:O', title='Years of Continuous Corn (2015–2020)'),y=alt.Y('count():Q', title='Number of Fields'),tooltip=['cc_years', 'count()']).properties(width=350,height=400,title='Continuous Corn Frequency')# -- Boxplot: Rotation Diversity by Land Use --rotation_box = alt.Chart(filtered).mark_boxplot().encode(x=alt.X('GenLU:N', title='General Land Use'),y=alt.Y('rotation_diversity:Q', title='Rotation Diversity'),color='GenLU:N',tooltip=['GenLU', 'rotation_diversity']).properties(title='Rotation Diversity by Land Use',width=800,height=400)# ---- Layout ----st.altair_chart(area_chart, use_container_width=True)st.altair_chart(scatter, use_container_width=True)st.altair_chart(cc_bar, use_container_width=True)st.altair_chart(rotation_box, use_container_width=True)# ---- Discussion Section ----st.subheader("🧾 How to Use This Dashboard")st.markdown("""This dashboard enables exploration of Illinois crop coverage, land use patterns, and crop rotation practices from 2010 to 2020.Due to the large size of the initial 2 datasets that were combined for this analysis, only a random sample (n=2000) ofeach dataset was collected to ensure dashboard performance. The author acknowledges that while this approach preservesgeneral trends and relationships, some patterns, like rare crop or land use combinations, may not be fully represented in the visualizations.Finally, this dashboard supports the identification of mono-cropping trends, crop diversity gaps, and sustainability challenges, especially in relation to water conservation.Use the sidebar to filter by crop types and general land use categories.* The area chart displays how total crop coverage changes over time.* The scatter plot relates crop coverage to rotation diversity by year, highlighting diversity trends.* The bar chart shows how frequently fields were planted with continuous corn, offering insight into back-to-back planting patterns.* The boxplot compares rotation diversity across different land use types, helping identify where more diverse rotations occur.Hover over chart elements for detailed values.""")# ---- Dataset Link ----st.subheader("🌍 Dataset Source")st.markdown("""The data is sourced from **Data.gov** and was collected by the USDA. [Agricultural land use by field: Illinois 2010-2020](https://catalog.data.gov/dataset/agricultural-land-use-by-field-illinois-2010-2020-114f7)""")# ---- Contextual Dataset Ideas ----st.subheader("🌍 Contextual Datasets")st.markdown("""- **Iowa Crop Rotation Data (CDL-based)** – To compare rotation practices in another high-production state. [USDA NASS CDL](https://www.nass.usda.gov/Research_and_Science/Cropland/Release/index.php)- **Illinois Soil Types and Drainage Classes** – To relate land use decisions to soil characteristics. [USDA NRCS Web Soil Survey](https://websoilsurvey.sc.egov.usda.gov/)""")# ---- Large File Note ----st.subheader("🗂️ Hosting Considerations")st.markdown("""This dataset does **not exceed GitHub’s file size limit**, and can be hosted directly within this HuggingFace Space.""")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import streamlit as stimport pandas as pdimport altair as altimport plotly.express as pxst.set_page_config(page_title="IL Crop Rotation Explorer", layout="wide")st.title("🌾 Illinois Crop Rotation and Land Use Exploration")st.markdown("Explore dominant crops and land use characteristics across Illinois fields from 2010–2020. This dashboard is for exploration and pattern recognition. Dashboard created by Sara Kiel.")# Load data@st.cache_datadef load_data():return pd.read_csv("crop_final_df.csv")df = load_data()# ---- Sidebar filters ----crop_options = sorted(df['crop_name'].dropna().unique())genlu_options = sorted(df['GenLU'].dropna().unique())selected_crops = st.sidebar.multiselect("Filter by Crop", options=crop_options, default=crop_options[:5])selected_genlu = st.sidebar.multiselect("Filter by General Land Use",options=genlu_options,default=genlu_options[:5])filtered = df[df['crop_name'].isin(selected_crops) &df['GenLU'].isin(selected_genlu)]# ---- Area chart: Crop coverage over time ----coverage = filtered.groupby(['year', 'crop_name'])['pct_crop'].sum().reset_index()area_chart = alt.Chart(coverage).mark_area(opacity=0.7).encode(x=alt.X('year:O', title='Year'),y=alt.Y('pct_crop:Q', title='Total Crop Coverage (%)'),color=alt.Color('crop_name:N', title='Crop'),tooltip=['year', 'crop_name', 'pct_crop']).properties(width=800,height=400,title='Crop Coverage Over Time')# ---- Scatter Plot: Crop Coverage vs Rotation Diversity ----scatter = alt.Chart(filtered).mark_circle(size=60).encode(x=alt.X('year:O', title='Year'),y=alt.Y('rotation_diversity:Q', title='Rotation Diversity'),color=alt.Color('crop_name:N', title='Crop'),size=alt.Size('pct_crop:Q', title='% Crop Coverage'),tooltip=['crop_name', 'year', 'pct_crop', 'rotation_diversity', 'GenLU']).properties(width=800,height=400,title='Crop Coverage vs. Rotation Diversity Over Time')# -- Prepare continuous corn data --df['cc_years'] = df['CCCount'].str.extract(r'(\d+):').astype(float)# -- Bar chart: Frequency of Continuous Corn Planting --cc_bar = alt.Chart(df).mark_bar().encode(x=alt.X('cc_years:O', title='Years of Continuous Corn (2015–2020)'),y=alt.Y('count():Q', title='Number of Fields'),tooltip=['cc_years', 'count()']).properties(width=350,height=400,title='Continuous Corn Frequency')# -- Boxplot: Rotation Diversity by Land Use --rotation_box = alt.Chart(filtered).mark_boxplot().encode(x=alt.X('GenLU:N', title='General Land Use'),y=alt.Y('rotation_diversity:Q', title='Rotation Diversity'),color='GenLU:N',tooltip=['GenLU', 'rotation_diversity']).properties(title='Rotation Diversity by Land Use',width=800,height=400)# ---- Layout ----st.altair_chart(area_chart, use_container_width=True)st.altair_chart(scatter, use_container_width=True)st.altair_chart(cc_bar, use_container_width=True)st.altair_chart(rotation_box, use_container_width=True)# ---- Discussion Section ----st.subheader("🧾 How to Use This Dashboard")st.markdown("""This dashboard enables exploration of Illinois crop coverage, land use patterns, and crop rotation practices from 2010 to 2020.Due to the large size of the initial 2 datasets that were combined for this analysis, only a random sample (n=2000) ofeach dataset was collected to ensure dashboard performance. The author acknowledges that while this approach preservesgeneral trends and relationships, some patterns, like rare crop or land use combinations, may not be fully represented in the visualizations.Finally, this dashboard supports the identification of mono-cropping trends, crop diversity gaps, and sustainability challenges, especially in relation to water conservation.Use the sidebar to filter by crop types and general land use categories.* The area chart displays how total crop coverage changes over time.* The scatter plot relates crop coverage to rotation diversity by year, highlighting diversity trends.* The bar chart shows how frequently fields were planted with continuous corn, offering insight into back-to-back planting patterns.* The boxplot compares rotation diversity across different land use types, helping identify where more diverse rotations occur.Hover over chart elements for detailed values.""")# ---- Dataset Link ----st.subheader("🔗 Dataset Source")st.markdown("""The data is sourced from **Data.gov** and was collected by the USDA. [Agricultural land use by field: Illinois 2010-2020](https://catalog.data.gov/dataset/agricultural-land-use-by-field-illinois-2010-2020-114f7)""")# ---- Contextual Dataset Ideas ----st.subheader("🌍 Contextual Datasets")st.markdown("""- **Iowa Crop Rotation Data (CDL-based)** – To compare rotation practices in another high-production state. [USDA NASS CDL](https://www.nass.usda.gov/Research_and_Science/Cropland/Release/index.php)- **Illinois Soil Types and Drainage Classes** – To relate land use decisions to soil characteristics. [USDA NRCS Web Soil Survey](https://websoilsurvey.sc.egov.usda.gov/)""")# ---- Large File Note ----st.subheader("🗂️ Hosting Considerations")st.markdown("""This dataset does **not exceed GitHub’s file size limit**, and can be hosted directly within this HuggingFace Space.""")
app.py+127-127