I am trying to fix a widget in my Jupyter notebook that is labeled Water Rescue. It is supposed to change the data table in the output to where it shows a list of dogs with the different breeds that meet the criteria of a water rescue dog, such as Labrador Retriever Mix, Chesa Bay Retr Mix, and Newfoundland Mix. It is also supposed to render a pie chart showing the percentages of those breeds.
However, whenever I click on the Water Rescue widget, it only renders a pie chart showing the percentages of the original data table. Is there something wrong with the query within my update_dashboard function? Here is my code:
ProjectTwoDashboard.ipynb
from jupyter_plotly_dash import JupyterDash
import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table as dt
from dash.dependencies import Input, Output, State
import os
import numpy as np
import pandas as pd
import base64
from pymongo import MongoClient
from bson.json_util import dumps
from IPython.display import Image
#### FIX ME #####
# change animal_shelter and AnimalShelter to match your CRUD Python module file name and class name
from animal_shelter import AnimalShelter
###########################
# Data Manipulation / Model
###########################
# FIX ME change for your username and password and CRUD Python module name
username = "accuser"
password = "Superman"
shelter = AnimalShelter(username, password)
# class read method must support return of cursor object
df = pd.DataFrame.from_records(shelter.read({}))
#########################
# Dashboard Layout / View
#########################
app = JupyterDash('ProjectTwo')
#FIX ME Add in Grazioso Salvareās logo
image_filename = 'Grazioso Salvare Logo.png' # replace with your own image
encoded_image = base64.b64encode(open(image_filename, 'rb').read())
#FIX ME Place the HTML image tag in the line below into the app.layout code according to your design
#FIX ME Also remember to include a unique identifier such as your name or date
#html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()))
app.layout = html.Div([
html.Div(id='hidden-div', style={'display':'none'}),
html.Center(html.Img(src='data.image/png;base64,{}'.format(encoded_image.decode()))),
html.Center(html.B(html.H1('SNHU CS-340 Dashboard'))),
html.Hr(),
html.Div(
#FIXME Add in code for the interactive filtering options. For example, Radio buttons, drop down, checkboxes, etc.
dcc.RadioItems(
id='filter-type',
options=[
{'label': 'Water Rescue', 'value': 'WR'},
{'label': 'Mountain or Wilderness', 'value': 'MWR'},
{'label': 'Disaster or Individual Tracking', 'value': 'DIT'},
{'label': 'Reset', 'value': 'RESET'}
],
value='RESET',
labelStyle={'display':'inline-block'})
),
html.Hr(),
dt.DataTable(
id='datatable-id',
columns=[
{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns
],
data=df.to_dict('records'),
#FIXME: Set up the features for your interactive data table to make it user-friendly for your client
#If you completed the Module Six Assignment, you can copy in the code you created here
editable=False,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable=False,
row_selectable=False,
row_deletable=False,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current=0,
page_size=10,
),
html.Br(),
html.Hr(),
#This sets up the dashboard so that your chart and your geolocation chart are side-by-side
html.Div(className='row',
style={'display' : 'flex'},
children=[
html.Div(
id='graph-id',
className='col s12 m6',
),
html.Div(
id='map-id',
className='col s12 m6',
),
html.H4("This is Vincent, computer science major")
])
])
#############################################
# Interaction Between Components / Controller
#############################################
@app.callback(
[Output('datatable-id','data'),
Output('datatable-id','columns')],
[Input('filter-type', 'value')])
def update_dashboard(filter_type):
### FIX ME Add code to filter interactive data table with MongoDB queries
if filter_type == 'WR':
df = pd.DataFrame(list(shelter.read({'$and': [{'sex_upon_outcome': 'Intact Female'},
{'$or': [
{'breed': 'Laborador Retriever Mix'},
{'breed': 'Chesa Bay Retr Mix'},
{'breed': 'Newfoundland Mix'},
{'breed': 'Newfoundland/Laborador Retriever'},
{'breed': 'Newfoundland/Australian Cattle Dog'},
{'breed': 'Newfoundland/Great Pyrenees'}
]},
{'$and': [{'age_upon_outcome_in_weeks': {'$gte': 26}},
{'age_upon_outcome_in_weeks': {'$lte': 156}}]
}]
})))
elif filter_type == 'MWR':
#Grazioso breeds and ages
df = pd.DataFrame(list(shelter.read({'$and': [{'sex_upon_outcome': 'Intact Male'},
{'$or': [
{'breed': 'German Shepherd'},
{'breed': 'Alaskan Malamute'},
{'breed': 'Old English Sheepdog'},
{'breed': 'Rottweiler'},
{'breed': 'Siberian Husky'}
]},
{'$and': [{'age_upon_outcome_in_weeks': {'$gte': 26}},
{'age_upon_outcome_in_weeks': {'$lte': 156}}]
}]
})))
#adjusts the read request for the desired dog type and status
elif filter_type == 'DRIT':
#breeds and ages
df = pd.DataFrame(list(shelter.read({'$and': [{'sex_upon_outcome': 'Intact Male'},
{'$or': [
{'breed': 'Doberman Pinscher'},
{'breed': 'German Shepherd'},
{'breed': 'Golden Retriever'},
{'breed': 'Bloodhound'},
{'breed': 'Rottweiler'}
]},
{'$and': [{'age_upon_outcome_in_weeks': {'$gte': 20}},
{'age_upon_outcome_in_weeks': {'$lte': 300}}]
}]
})))
#resets the search no filter
elif filter_type == 'RESET':
df = pd.DataFrame.from_records(shelter.read({}))
columns=[{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns]
data=df.to_dict('records')
return (data,columns)
@app.callback(
Output('datatable-id', 'style_data_conditional'),
[Input('datatable-id', 'selected_columns')]
)
def update_styles(selected_columns):
return [{
'if': { 'column_id': i },
'background_color': '#D2F3FF'
} for i in selected_columns]
@app.callback(
Output('graph-id', "children"),
[Input('datatable-id', "derived_viewport_data")])
def update_graphs(viewData):
###FIX ME ####
dff = pd.DataFrame.from_dict(viewData)
names = dff['breed'].value_counts().keys().tolist()
values = dff['breed'].value_counts().tolist()
# add code for chart of your choice (e.g. pie chart)
return [
dcc.Graph(
figure = px.pie(
data_frame = dff,
values = values,
names = names,
color_discrete_sequence=px.colors.sequential.RdBu,
width = 800,
height = 500
)
)
]
@app.callback(
Output('map-id', "children"),
[Input('datatable-id', "derived_viewport_data"),
Input('datatable-id', 'selected_rows'),
Input('datatable-id', 'selected_columns')])
def update_map(viewData, selected_rows, selected_columns):
#FIXME: Add in the code for your geolocation chart
#If you completed the Module Six Assignment, you can copy in the code you created here.
dff = pd.DataFrame.from_dict(viewData)
if selected_rows == []:
selected_rows = [0]
# Austin TX is at [30.75, -97.48]
if len(selected_rows) == 1:
return [
dl.Map(style={'width':'1000px', 'height': '500px'}, center=[30.75,-97.48], zoom=10, children=[
dl.TileLayer(id="base-layer-id"),
#marker with tool tip and popup
dl.Marker(position=[(dff.iloc[selected_rows[0],13]), (dff.iloc[selected_rows[0],14])], children=[
dl.Tooltip(dff.iloc[selected_rows[0],4]),
dl.Popup([
html.H4("Animal Name"),
html.P(dff.iloc[selected_rows[0],9]),
html.H4("Sex"),
html.P(dff.iloc[selected_rows[0],12]),
html.H4("Breed"),
html.P(dff.iloc[selected_rows[0],4]),
html.H4("Age"),
html.P(dff.iloc[selected_rows[0],15])
])
])
])
]
app
animal_shelter.py
from pymongo import MongoClient
from bson.objectid import ObjectId
from bson.json_util import dumps
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self,username,password):
# Initializing the MongoClient. This helps to
# access the MongoDB databases and collections.
# init to connect to mongodb without authentication
self.client = MongoClient('mongodb://localhost:55996')
# init connect to mongodb with authentication
#self.client = MongoClient('mongodb://%s:%s@localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
self.database = self.client['AAC']
# Complete this create method to implement the C in CRUD.
def create(self, data):
if data is not None:
self.database.animals.insert(data) # data should be dictionary
return True # Tells whether the create function ran successfully
else:
raise Exception("Nothing to save ...")
# Create method to implement the R in CRUD.
def read(self, data):
if data:
cursor = self.database.animals.find(data, {'_id':False})
else:
cursor = self.database.animals.find({}, {"_id": False})
return cursor
# Update method to implement the U in CRUD.
def update(self, data, new_values):
updated_data = {"name":"Rhonda","age_upon_outcome":"2 years"}
if self.database.animals.count(data):
self.database.animals.update(data, new_values)
cursor = self.database.animals.find(updated_data)
json_data = dumps(cursor)
return json_data
else:
raise Exception("Nothing to update ...")
# Delete method to implement the D in CRUD
def delete(self, data):
result = self.database.animals.find_one_and_delete(data)
# print the _id key only if the result is not None
if("_id" in result):
print("find_one_and_delete ID:",result["_id"])
else:
print("Nothing to delete")