Pakistan Population Census 2017

1 Pakistan Population Census 2017

#| standalone: true
#| viewerHeight: 420
from pathlib import Path
from htmltools import css
from shiny import App, reactive, render, ui
import pandas as pd
from shinywidgets import output_widget, reactive_read, register_widget
from ipywidgets import Text, HTML
import ipywidgets as widgets
import json
import ipyleaflet as L
from branca.colormap import linear
import seaborn as sns



infile1 = Path(__file__).parent / "PakPC2017Merged.csv"
data = pd.read_csv(infile1)
provinceOption = data.Province.unique().tolist()


infile2 = Path(__file__).parent / "data.geojson"
with open(infile2) as f:
    geojson = json.load(f)
    
jso2 = pd.json_normalize(geojson, "features")
jso3 = dict(zip(jso2["properties.NAME_EN"].tolist(), jso2["properties.Pop2017"].tolist()))

for feature in geojson['features']:
    properties = feature['properties']
    feature.update(id=properties['NAME_EN'])
    #print(feature['id'])





app_ui = ui.page_fluid(
    ui.panel_title("Population Census 2017"),
    ui.navset_tab_card(
####################################################################    
        ui.nav("Data", ui.output_table("table"),
        ),
####################################################################
        ui.nav("Plots",
            ui.layout_sidebar(
                ui.panel_sidebar(
                ui.input_radio_buttons("radio", "Plot by ", ["Province", "Division", "District"],selected="Province"),
                ui.panel_conditional(
                "input.radio == 'Province' | input.radio == 'Division' | input.radio == 'District'", 
                ui.input_selectize("province_select", "Select input", provinceOption, multiple = True),
                ),
                ui.panel_conditional(
                "input.radio == 'Division' | input.radio == 'District'",
                ui.input_selectize("division_select", "Select input", [], multiple=True),
                ),
                ui.panel_conditional(
                "input.radio === 'District'",
                ui.output_ui("district_dist"),
                ),
                
                #ui.input_selectize("province_select", "Select input", provinceOption, multiple = True),
                #ui.input_selectize("di_select", "Select input", [], multiple=True),
                ),
                ui.panel_main(
                ui.output_plot("plot"),
                ),
            )
        ),
        
###################################################################        
        ui.nav("Geographic Map", output_widget("map")
        ),
        
        
##################################################################
    )
)



def server(input, output, session):
    #geo_json = L.GeoJSON(
    #data=geojson,
    #hover_style={'fillColor': '#b08a3e' , 'fillOpacity': 0.8},
    #name = 'NAME_EN'
    # layer = L.Choropleth(
    # geo_data=geojson,
    # choro_data=jso3,
    # colormap=linear.YlOrRd_04,
    # border_color='black',
    # style={'fillOpacity': 0.8, 'dashArray': '5, 5'})
    # 
    # 
    # map = L.Map(center=(31.41, 73.092), zoom=5
    # , scroll_wheel_zoom=True)
    # map.add_layer(layer)
    # 
    # for name, population, lon, lat in jso2[["properties.NAME_EN", "properties.Pop2017", "properties.lon", "properties.lat"]].values:
    #     #message = HTML(value="%s : %d"%(name, population))
    #     marker = L.Marker(location=(lat,lon))
    #     #popup = L.Popup(location=(lat, lon), child=message, close_button=False, auto_close=False, close_on_escape_key=False)
    # # map.add_layer(marker)
    # 
    # 
    # # Add a distance scale
    # map.add_control(L.leaflet.ScaleControl(position="bottomleft"))
    # #register_widget("map", map)
    # 
    # html = widgets.HTML("Hover Over Countries")
    # #html.layout.margin = '0px 20px 20px 20px'
    # widget_control1 = L.WidgetControl(widget=html, position='topright')
    # #map.add_control(widget_control1)
    # #register_widget("map", map)
    # 
    # color_picker = widgets.ColorPicker(description='Pick a color:')
    # widget_control2 = L.WidgetControl(widget=color_picker, position='bottomright')
    # map.add_control(widget_control2)
    # register_widget("map", map)

    @output
    @render.table
    def table():
        return (
                data.style.set_table_attributes(
                    'class="dataframe shiny-table table w-auto"'
                )
                .format(
                    {
                        "Households": "{:.0f}",
                        "Male": "{:.0f}",
                        "Female": "{:.0f}",
                        "Transgender": "{:.0f}",
                        "Pop2017": "{:.0f}",
                        "Pop1998": "{:.0f}",
                        "SexRatio2017": "{:.2f}",
                        "GrowthRate": "{:.2f}",
                    }
                )
               )
    # @reactive.Effect()
    # def _():
    #     x = input.province_select()
    #     data1 = data[data.Province.isin(x)]
    #     divisionOption = data1.Division.unique().tolist()
    #     ui.update_select(
    #         "division_select",
    #         #label=f"Select input ({len(x)} options)",
    #         choices=divisionOption,
    #         selected=None,
    #     )
    # 
    # @output(id="district_dist")
    # @render.ui
    # def _():
    #     y = input.division_select()
    #     data1 = data[data.Division.isin(y)]
    #     districtOption = data1.District.unique().tolist()
    #     return ui.input_selectize(
    #         "district_select", "Select Districts to Plot", districtOption, multiple=True
    #     )
    #     
    # 
    # 
    # @output
    # @render.plot
    # def plot():
    #     p = input.radio()
    #     x = input.province_select()
    #     y = input.division_select()
    #     z = input.district_select()
    #     if p == 'Province':
    #         data1 = data[data['Province'].isin(x)]
    #         df = data1.groupby(p, as_index = False).agg({"Pop2017":"sum"})
    #     elif p == 'Division':
    #         data1 = data[data['Division'].isin(y)]
    #         df = data1.groupby(['Province','Division'], as_index = False).agg({"Pop2017":"sum"})
    #     else:
    #         data1 = data[data['District'].isin(z)]
    #         df = data1.groupby(['Province','District'], as_index = False).agg({"Pop2017":"sum"})
    #         
    #     g = sns.FacetGrid(df, col="Province",col_wrap=2)
    #     g.map_dataframe(sns.barplot, x=p, y='Pop2017')
    #     
    #     
    # 
    #     


app = App(app_ui, server)