Py.Cafe

mikefinko77/

dash-raleigh-building-permits-analysis

Raleigh Building Permits Analysis

DocsPricing
  • assets/
  • Building_Permits_Issued_Past_180_Days.csv
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# check out https://dash.plotly.com/ for documentation
# And check out https://py.cafe/maartenbreddels for more examples
import dash
from dash import dcc, html, Input, Output
import plotly.express as px
import pandas as pd

# Load the data
df = pd.read_csv('Building_Permits_Issued_Past_180_Days.csv')

# Initialize the Dash app
app = dash.Dash(__name__, suppress_callback_exceptions=True)

# Add global CSS styling
app.index_string = '''
<!DOCTYPE html>
<html>
    <head>
        {%metas%}
        <title>{%title%}</title>
        {%favicon%}
        {%css%}
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
        <style>
            * {
                font-family: Arial, sans-serif !important;
            }
            body {
                background-image: url('assets/construction_site.jpg');
                background-size: cover;
                background-position: center;
                background-attachment: fixed;
                background-repeat: no-repeat;
                margin: 0;
                padding: 0;
            }
            body::before {
                content: '';
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(255, 255, 255, 0.5);
                z-index: -1;
            }
        </style>
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            {%renderer%}
        </footer>
    </body>
</html>
'''

# Define the layout
app.layout = html.Div([
    html.Div([
        html.H1("Raleigh Building Permits Analysis", 
                style={'textAlign': 'center', 'marginBottom': 10, 'fontFamily': 'Arial'}),
        

        
        dcc.Tabs(id="main-tabs", value='project-types-tab', children=[
            dcc.Tab(
                label='📋 Project Types', 
                value='project-types-tab', 
                style={'fontFamily': 'Arial'}
            ),
            dcc.Tab(
                label='⛑️ Top Contractors', 
                value='contractors-tab', 
                style={'fontFamily': 'Arial'}
            ),
        ], style={'fontFamily': 'Arial'}),
        
        html.Div(id='tabs-content', style={'marginTop': 30})
        
    ], style={'width': '75%', 'margin': '0 auto', 'padding': '20px', 'backgroundColor': 'rgba(255, 255, 255, 0.95)', 'borderRadius': '15px', 'boxShadow': '0 4px 15px rgba(0,0,0,0.1)', 'marginTop': '20px', 'marginBottom': '20px'})
], style={'fontFamily': 'Arial'})

# Callback to render tab content
@app.callback(
    Output('tabs-content', 'children'),
    Input('main-tabs', 'value')
)
def render_content(tab):
    if tab == 'project-types-tab':
        return html.Div([
            html.Div([
                html.Label("Permit Class:", style={'fontWeight': 'bold', 'marginBottom': 10, 'fontFamily': 'Arial'}),
                dcc.RadioItems(
                    id='permit-class-radio',
                    options=[
                        {'label': 'Residential', 'value': 'Residential'},
                        {'label': 'Non-Residential', 'value': 'Non-Residential'}
                    ],
                    value='Residential',
                    style={'marginBottom': 30, 'fontFamily': 'Arial'}
                )
            ], style={'textAlign': 'center'}),
            
            dcc.Graph(id='project-type-chart')
        ])
    
    elif tab == 'contractors-tab':
        return html.Div([
            html.Div([
                html.Label("Permit Class:", style={'fontWeight': 'bold', 'marginBottom': 10, 'fontFamily': 'Arial'}),
                dcc.RadioItems(
                    id='contractor-permit-class-radio',
                    options=[
                        {'label': 'Residential', 'value': 'Residential'},
                        {'label': 'Non-Residential', 'value': 'Non-Residential'}
                    ],
                    value='Residential',
                    style={'marginBottom': 30, 'fontFamily': 'Arial'}
                )
            ], style={'textAlign': 'center'}),
            
            html.Div(id='outlier-text', style={'textAlign': 'center', 'marginBottom': 20, 'fontFamily': 'Arial', 'fontStyle': 'italic', 'color': '#666'}),
            
            dcc.Graph(id='contractor-bubble-chart')
        ])

# Callback to update the chart based on radio button selection
@app.callback(
    Output('project-type-chart', 'figure'),
    Input('permit-class-radio', 'value')
)
def update_chart(selected_class):
    # Filter data based on selected permit class
    filtered_df = df[df['permit_class_mapped'] == selected_class]
    
    # Count project types
    project_counts = filtered_df['class_work'].value_counts().reset_index()
    project_counts.columns = ['Project Type', 'Count']
    
    # Create horizontal bar chart
    fig = px.bar(
        project_counts, 
        x='Count', 
        y='Project Type',
        orientation='h',
        title=f'Project Types - {selected_class} Permits',
        labels={'Count': 'Number of Permits', 'Project Type': 'Project Type'}
    )
    
    # Update layout for better appearance
    fig.update_layout(
        height=600,
        yaxis={'categoryorder': 'total ascending'},
        margin=dict(l=150, r=50, t=80, b=50),
        font=dict(family="Arial")
    )
    
    return fig

# Callback for contractor bubble chart
@app.callback(
    [Output('contractor-bubble-chart', 'figure'),
     Output('outlier-text', 'children')],
    Input('contractor-permit-class-radio', 'value')
)
def update_contractor_chart(selected_class):
    # Filter data based on selected permit class
    filtered_df = df[df['permit_class_mapped'] == selected_class]
    
    # Remove null contractor names and calculate contractor metrics
    contractor_df = filtered_df[filtered_df['contractor_company_name'].notna()]
    
    contractor_summary = contractor_df.groupby('contractor_company_name').agg({
        'contractor_company_name': 'count',  # Number of contracts
        'estimated_project_cost': ['sum', 'mean']  # Total and average cost
    }).reset_index()
    
    # Flatten column names
    contractor_summary.columns = ['contractor_company_name', 'number_of_contracts', 'total_estimated_cost', 'avg_contract_price']
    
    # Filter out Evans General Contractors for Non-Residential
    if selected_class == 'Non-Residential':
        contractor_summary = contractor_summary[contractor_summary['contractor_company_name'] != 'Evans General Contractors']
    
    # Sort by total estimated cost and take top 15
    contractor_summary = contractor_summary.sort_values('total_estimated_cost', ascending=False).head(15)
    
    # Create bubble chart
    fig = px.scatter(
        contractor_summary,
        x='number_of_contracts',
        y='avg_contract_price',
        size='total_estimated_cost',
        hover_name='contractor_company_name',
        hover_data={
            'number_of_contracts': True,
            'avg_contract_price': ':,.2f',
            'total_estimated_cost': ':,.0f'
        },
        title=f'Top Contractors - {selected_class} Permits',
        labels={
            'number_of_contracts': 'Number of Contracts',
            'avg_contract_price': 'Average Contract Price ($)',
            'total_estimated_cost': 'Total Contracts ($)'
        }
    )
    
    # Update layout
    fig.update_layout(
        height=600,
        margin=dict(l=80, r=50, t=80, b=50),
        font=dict(family="Arial")
    )
    
    # Format y-axis as currency
    fig.update_yaxes(tickformat='$,.0f')
    
    # Handle outlier text for Non-Residential
    outlier_text = ""
    if selected_class == 'Non-Residential':
        outlier_text = "Note: Evans General Contractors excluded from chart (1 contract, $80,544,979)"
    
    return fig, outlier_text

# Run the app
if __name__ == '__main__':
    app.run(debug=True)