dibend/US-State-Zip-Code-3D-Correlation-Matrix
0
1import gradio as gr2import pandas as pd3import plotly.graph_objects as go4import numpy as np5 6def plot_real_estate_correlation(state):7 # Read the CSV file8 df = pd.read_csv('https://files.zillowstatic.com/research/public_csvs/zhvi/Zip_zhvi_uc_sfrcondo_tier_0.33_0.67_sm_sa_month.csv')9 10 # Filter for the given state11 df = df[df['State'] == state.upper()]12 13 # Extract the list of ZIP codes and filter only columns that are date strings14 zip_codes = df['RegionName'].unique()15 16 # Extract columns that are valid date strings only17 date_columns = []18 for col in df.columns[7:]:19 try:20 # Try to parse column names as dates21 pd.to_datetime(col)22 date_columns.append(col)23 except:24 continue25 26 # Initialize a DataFrame to hold price data for correlation calculation27 price_matrix = []28 29 # Loop through each ZIP code in the state30 for zip_code in zip_codes:31 df_zip = df[df['RegionName'] == zip_code]32 33 # Extract only the columns with valid date data (price values)34 prices = df_zip.loc[:, date_columns].values.flatten()35 36 # Append prices to the matrix if there are no missing values37 if not np.isnan(prices).all():38 price_matrix.append(prices)39 40 # Convert to DataFrame for easier manipulation41 price_matrix_df = pd.DataFrame(price_matrix, index=zip_codes, columns=date_columns)42 43 # Transpose to align for correlation calculation (each column = ZIP code)44 price_matrix_df = price_matrix_df.T.dropna()45 46 # Calculate the correlation matrix for ZIP codes47 corr_matrix = price_matrix_df.corr()48 49 # Prepare the grid data for 3D plot50 z_data = corr_matrix.values51 x_data, y_data = np.meshgrid(zip_codes, zip_codes)52 53 # Create the 3D surface plot54 fig = go.Figure(data=[go.Surface(z=z_data, x=x_data, y=y_data)])55 56 # Update plot layout57 fig.update_layout(58 title=f'3D Correlation Matrix of Housing Prices in {state}',59 scene=dict(60 xaxis_title='ZIP Code',61 yaxis_title='ZIP Code',62 zaxis_title='Correlation',63 ),64 autosize=True65 )66 67 return fig68 69iface = gr.Interface(fn=plot_real_estate_correlation,70 inputs=[gr.components.Textbox(label="State (e.g., 'NJ' for New Jersey)")],71 outputs=gr.Plot())72 73iface.launch(share=False, debug=True)