Py.Cafe

marie-anne/

2025-figurefriday-w8

A bit of px.strip, a lot of animal welfare

DocsPricing
  • assets/
  • 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
## I am so sorry for this code but I was in a hurry
## and wanted to make something. Do not try this at home.
## and not responsive at all.

from dash import Dash, dcc, html
import plotly.express as px
import pandas as pd
import numpy as np
import statistics
import dash_bootstrap_components as dbc

df = pd.read_csv("https://raw.githubusercontent.com/plotly/Figure-Friday/refs/heads/main/2025/week-8/Dallas_Animal_Shelter_Data_Fiscal_Year_Jan_2024.csv")
df["Intake_Date"] = pd.to_datetime(df['Intake_Date'])
df["Outcome_Date"] = pd.to_datetime(df['Outcome_Date'])
df["Animal_Stay_Days"] = (df["Outcome_Date"] - df["Intake_Date"]).dt.days

#FILTER ON LIVING DOGS

df_filtered = df[(df["Animal_Type"] == "DOG") & (df['Intake_Type'] != "DISPOS REQ")]

#CUSTOMTOOLTIPDATA IS USED IN THE ANNOTATIONS, original plan was tooltips but they were acting funny
customtooltipdata = df_filtered.groupby('Intake_Type').agg(
    
    numberDogs = pd.NamedAgg(column='Animal_Id', aggfunc='count'),
    medianDays = pd.NamedAgg(column='Animal_Stay_Days', aggfunc='median'),
    maxDays = pd.NamedAgg(column='Animal_Stay_Days', aggfunc='max'),
    
    ).reset_index()

def create_annotation(intaketype):
    annotationtext = ''
    annotationtext += f"<b>{intaketype}</b>: <br>"
    annotationtext +=f"Dogs taken in: <b>{customtooltipdata[customtooltipdata['Intake_Type']== intaketype]['numberDogs'].values[0]}</b><br>"
    annotationtext +=f"50% leave within <b>{customtooltipdata[customtooltipdata['Intake_Type']== intaketype]['medianDays'].values[0]:.0f}</b> days, but<br>"
    annotationtext +=f"the max. stay was <b>{customtooltipdata[customtooltipdata['Intake_Type']== intaketype]['maxDays'].values[0]:.0f}</b> days."
    
    return annotationtext

### create link to Leo's (the dog) organisation to be correct #####

def create_link_newyork():
        
    link_nyc = html.A("Social Tees Animal Rescue", href='https://socialteesnyc.org/', target="_blank"),
        
    return link_nyc

#CREATE THE FIGURE

color_discrete_sequence=["rgba(0,0,0,.5)", "rgba(0,0,0,.5)", "rgba(0,0,0,.5)", "rgba(0,0,0,.5)", "rgba(0,0,0,.5)", "rgba(0,0,0,.5)", "rgba(0,0,0,.5)"]

fig = px.strip(df_filtered, x="Intake_Type", y="Animal_Stay_Days", height=600, color='Intake_Type', color_discrete_sequence=color_discrete_sequence)

fig.layout.update(showlegend=False, 
                  margin=dict(l=5, r=5, t=25, b=5),
                  plot_bgcolor='white'
                  
                  )

fig.update_yaxes(title='Days', visible=True, showgrid=True, gridwidth=1, gridcolor='#40c2ac'
                 , griddash='dot',
                 range = [0,150]
                 )
fig.update_xaxes(title='', visible=True)
fig.update_traces(hoverinfo='skip', hovertemplate=None) 

fig.add_annotation(x=0.3, y=142,
            text=create_annotation('STRAY'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )

fig.add_annotation(x=1.0, y=70,
            text=create_annotation('CONFISCATED'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )
fig.add_annotation(x=2.0, y=43,
            text=create_annotation('FOSTER'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )
fig.add_annotation(x=3.0, y=72,
            text=create_annotation('OWNER SURRENDER'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )
fig.add_annotation(x=4.0, y=30,
            text=create_annotation('TREATMENT'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )
fig.add_annotation(x=5.0, y=55,
            text=create_annotation('KEEPSAFE'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )
fig.add_annotation(x=6.0, y=70,
            text=create_annotation('TRANSFER'),
            showarrow=False,
            bgcolor = 'rgba(64, 194, 172,.3)',
            borderpad = 4,
            align='left',
            font=dict(color='black')
            )


#THE APP with far too much styling inside
dbc_css = "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates/dbc.min.css"
app = Dash(__name__, external_stylesheets=[dbc.themes.MATERIA, dbc_css])


app.layout = dbc.Container([
    dbc.Container([
   dbc.Row([dbc.Col([
           html.Div(html.Img(src='assets/logodas.webp', 
                 alt='Logo Dallas Animal Services', className='circle', style={'maxWidth':'100px'})),
           html.Div([
                   html.H3('Dallas Animal Services', style={'paddingLeft':'1rem'}),
                   html.P('Animal welfare professionals from across the country have come to DAS to be a part of the ground-breaking Dallas90 initiative. Our team includes nearly 200 dedicated individuals who believe in our lifesaving mission\
                          and are working hard to make Dallas the best city in the country for pets and pet owners! ', style={'padding':'1rem'})
                   
                   ]),
               
              
               ],className='col-md-9', style={'display':'flex', 'flexDirection':'row','alignContent':'flex-start'}),
            dbc.Col([
                html.A("Find your dog", href='https://bedallas90.org/home/pets/', target="_blank", className='btn btn-success', style={'marginLeft':'1rem'}),
  
                html.A("Donate", href='https://www.friendsofdas.org/donate', target="_blank", className='btn btn-warning', style={'marginLeft':'1rem'}),
              ],className='col-md-3', style={'display':'flex', 'flexDirection':'row-reverse'})
            ], style={'backgroundColor':'#d8d8d8','padding':'1rem','alignItems':'center'}),
   dbc.Row([
       dbc.Col([
                html.P('At this moment (21 feb 2025), more dogs need to be taken in than there is space in the kennels. The status is critical overflow, we need your help! We could use equipment (see Donate) or maybe you are thinking about a new dog?',className='bg-warning', style={'fontWeight':'bold','padding':'1rem'} ),
                html.H4('How many days does a dog spend in our shelter?'),
                html.P('Impression: below you see the figures for the dogs which were taken in in januari 2024, grouped by the reason why. Every dot is a dog!'),
                dcc.Graph(figure=fig)],className='col-md-9'),
       dbc.Col([html.H2('Meet Leo!', style={'marginTop':'1rem'}),
                html.Img(src='assets/leo-before.jpg', alt='Leo before',  style={'maxWidth':'100%','marginTop': '1rem','marginBottom':'1rem','borderRadius':'10px'}),
                html.P('Leo was a tiny puppy from a backyard breeder who was "getting rid of" the last of the litter. Lucky for Leo, a smart NYC resident adopted him from Social Tees Animal Rescue, a not-for-profit, strictly no-kill organization in New York. Look him glow! Are you living in New York and thinking about a new dog? The link is below "Happy Leo".'),
                html.Img(src='assets/leo-after.jpg', alt='Leo after', style={'maxWidth':'100%','marginBottom':'1rem','borderRadius':'10px'}),
                html.A("Social Tees Animal Rescue", href='https://socialteesnyc.org/', target="_blank", style={'color': 'black', 'fontWeight':'bold'})]
               ,className='col-md-3', style={'backgroundColor':'#f0f0f0'})
       
       ],style={'marginTop':'1rem'})
    
    
   ], fluid=False, style={'backgroundColor':'white'}), 
    
    
], fluid = True, style={'backgroundColor':'#40c2ac'})


if __name__ == "__main__":
    app.run(debug=True)