{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Environmental Justice"},{"metadata":{},"cell_type":"markdown","source":"The challenge requires us to link social and environmental justice.\nI found myelf wondering about possible interactions between these 2 fields. \n\nFortunately the city of Berlin has responded to the only question in the cdp report directly targeted at the social impact of climate actions: \n\n> Has your city measured and demonstrated the wider social and economic impacts of delivering climate actions/projects/policies? If so, please provide more details and a link to more information.\n\nUnlike other cities Berlin has already put measures into place and link their detailed plan of measureing Environmental Justice in Berlin and how they couple this to investments.\n\nThe Dataset consists of 5 Main indicators for Environmental Justice summarized to the easy understandable rating of very low, low, middle and high fully based on objective parameters for the 447 planning areas of Berlin:\n    1. Noise\n        (noise costs (the harm caused per person by the impact of the disturbance and the health risks as a sum) per inhabitant)\n    2. Air Pollution\n        (measured using PM2.5 + NO2 annual average)\n    3. Supply of Green Areas\n        (available Green Area per Person)\n    4. Social Status\n        (Social Urban Development Monitoring 2013, which relies on a set of six status and six dynamic indicators from the field of social reporting)\n    5. Bioclimatic Stres\n        (using the physiological equivalent temperature at night and day)\n        \nFor more information visit: https://www.stadtentwicklung.berlin.de/umwelt/umweltatlas/ei901.htm\n    \nThis data clearly shows how Environmental and Social issues are interlinked even on a city scale level. \n\nFuture work may focus on linking environmental justice on different scales such as finding Trends resembled on City and Global scales.\n\nI here show you how to explore and visualise this dataset. \n\n"},{"metadata":{},"cell_type":"markdown","source":"### Table of Contents"},{"metadata":{},"cell_type":"markdown","source":"1. Berlin, Germany - A Case Study of measureing Enrivonmental Justice: \n    - Identifying KPIs on a city scale, which relate to the environmental and social issues that are discussed in the CDP survey data"},{"metadata":{},"cell_type":"markdown","source":"## Berlin, Germany - A Case Study of measureing Enrivonmental Justice"},{"metadata":{},"cell_type":"markdown","source":"![](https://static.ticketbar.eu/_1980x1320_/berlin/classificaties/rabattkarten/berlin-online-city-pass/berlincitypass_header-1516978149-1518186949.jpg)"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"##imports\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport geopandas as gpd\n\nimport geopandas as gpd\nimport pandas as pd\nimport shapely.geometry\nfrom shapely.geometry import Polygon\nimport json\n\nimport plotly.graph_objects as go\nimport pandas as pd\nimport numpy as np\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nimport plotly.express as px","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#load dataframes\ndf_berlin = pd.read_csv(\"../input/environmental-justice-in-berlin-city/BER_environmental_justice.csv\")\n\nberlin_neighbourhoods_df = gpd.read_file('../input/environmental-justice-in-berlin-city/LOR-Planungsraeume.geojson')\nberlin_neighbourhoods_df = berlin_neighbourhoods_df.sort_values(by = \"Name\").reset_index(drop = True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualisation"},{"metadata":{},"cell_type":"markdown","source":"### Social Status"},{"metadata":{},"cell_type":"markdown","source":"Here you see the Social Status among all 447 Berlin planning areas.\n\nYou can hover, zoom in and out to get more detailed information on each neighbourhood. "},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# Data\ncols_dd = ['Social Status']\nvalue = ['Social Status']\n# we need to add this to select which trace \n# is going to be visible\nvisible = np.array(cols_dd)\n\ntraces = []\nbuttons = []\n\n    \ng = gpd.GeoSeries(berlin_neighbourhoods_df.geometry.tolist())\n\npoly_json = json.loads(g.to_json())\n\ndf = pd.DataFrame([np.arange(len(berlin_neighbourhoods_df)), df_berlin[value].values.flatten()]).T\ndf.columns = [\"id\", \"color\"]\n        \nlabels = ['Very Low','Low','Middle', \"High\"]\n\ntraces.append(go.Choropleth(geojson=poly_json,\n                            locations=df['id'].astype(str),\n                            autocolorscale = False,\n                            z = df['color'].astype(float),\n                            zauto = False,\n                            zmin = 1, \n                            zmax = 4,\n                            colorbar=dict(\n                                thicknessmode=\"pixels\",\n                                lenmode=\"fraction\",\n                                yanchor=\"top\",y=1,\n                                ticks=\"outside\",\n                                tickvals=[1,2,3,4],\n                                ticktext=labels,\n                                dtick=4),\n                            showlegend = False,\n                            colorscale=[[0, 'rgb(60,60,255)'],\n                                        [1, 'rgb(255,60,60)']],))\n\n\nfig = go.Figure()\n\n\nfig.add_trace(traces[0])\n\nfig.update_geos(fitbounds=\"locations\", visible=False)\n\n\nfirst_title = cols_dd[0]\nfig.update_layout(title=f\"<b>{first_title}</b>\",title_x=0.5,\n    autosize=True,\n    )\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Bringing together environmental and social indicators"},{"metadata":{},"cell_type":"markdown","source":"Here we plot the different environmental factors in a choropleth plot and plot PieCharts to visualise the environmental factors in neighbourhoods with different social statuses. \n\nWe can clearly see that with higher social status a neighbourhood is less noisy, has more access to green areas, the air is less polluted and bioclimatic stress is reduced. \n\nPer example: Below you can see that nearly 50% of neighbourhoods with high social status have low / very low air pollution , while only < 15% of neighbourhoods with middle and low and very low social status have low / very low air pollution.\n\n\n\nYou can select the different environmental KPIs in the drop down menu at the top. "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Data\ncols_dd = ['Air Pollution (PM2.5 + NO2)', \n        'Noise',\n        'Grean area supply', \n        'Bioclimatic Stress', ]\n# we need to add this to select which trace \n# is going to be visible\nvisible = np.array(cols_dd)\n\n# define traces and buttons at once\ntraces = []\npiecharts = []\nbuttons = []\n\n#loop through environmental factors\nfor idx, value in enumerate(cols_dd):\n    \n    #define all relevant dataframes for the plot\n    g = gpd.GeoSeries(berlin_neighbourhoods_df.geometry.tolist())\n\n    poly_json = json.loads(g.to_json())\n\n    df = pd.DataFrame([np.arange(len(berlin_neighbourhoods_df)), df_berlin[value]]).T\n    df.columns = [\"id\", \"color\"]\n\n            \n    labels = ['Very Low','Low','Middle', \"High\"]\n    \n    #add the different choropleth maps\n    traces.append(go.Choropleth(geojson=poly_json,\n                                locations=df['id'].astype(str),\n                                autocolorscale = False,\n                                z = df['color'].astype(float),\n                                zauto = False,\n                                zmin = 1, \n                                zmax = 4,\n                                colorbar=dict(\n                                    thicknessmode=\"pixels\",\n                                    lenmode=\"fraction\",\n                                    yanchor=\"top\",y=1, len=0.3,\n                                    ticks=\"outside\",\n                                    tickvals=[1,2,3,4],\n                                    ticktext=labels,\n                                    dtick=4),\n                                showlegend = False,\n                                colorscale=[[0, 'rgb(60,60,255)'],\n                                            [1, 'rgb(255,60,60)']],))\n    \n    #so that there is no visualisation error\n    boolx = True\n    \n    if(idx) > 0:\n        boolx = False\n\n    #pie chart color\n    berlin_colors = ['rgb(255,60,60)', 'rgb(180, 60, 255)', 'rgb(120, 60, 255)', 'rgb(60,60,255)']\n    \n    #create pie charts\n    for i in range(1, 5):\n        values = [\n                    (df_berlin[df_berlin[\"Social Status\"] == i][value] == 4).sum(), \n                    (df_berlin[df_berlin[\"Social Status\"] == i][value] == 3).sum(), \n                    (df_berlin[df_berlin[\"Social Status\"] == i][value] == 2).sum(), \n                    (df_berlin[df_berlin[\"Social Status\"] == i][value] == 1).sum()]\n        \n        labels = [\"High\", 'Middle','Low', 'Very Low']\n\n        piecharts.append(go.Pie(labels=labels, values=values, showlegend = True, visible = boolx, marker_colors=berlin_colors, sort = False))\n    \n    #create drop down\n    buttons.append(dict(label=value.split(\":\")[0],\n                        method=\"update\",\n                        args=[{\"visible\":list(visible==value)},\n                              {\"title\":f\"<b>{value}</b>\"}]))\n\n#drop down design\nupdatemenus = [{\"active\":0,\n                \"buttons\":buttons,\n                \"direction\":\"down\",\n                \"x\":0.05,\n                \"xanchor\":\"left\",\n                \"y\":1.02,\n                \"yanchor\":\"top\"\n               }]\n\n\n#make subplots \nfig = make_subplots(\n    rows=4, cols=2,\n    \n    specs=[[{\"rowspan\": 2, \"colspan\": 2, 'type': 'choropleth'}, None],\n           [None, None],\n          [{'type': 'pie'}, {'type': 'pie'}],\n          [{'type': 'pie'}, {'type': 'pie'}]],\n    \n    subplot_titles=(\"\", \"high Social Status\", \"medium Social Status\", \"low Social Status\",  \"very low Social Status\"),\n    \n    print_grid=False)\n\n## add traces to Figure in the correct order\nfor i in range(len(cols_dd)):\n    fig.add_trace((traces[i]), 1, 1)\nfor i in range(len(cols_dd)):\n    fig.add_trace((piecharts[4 * i + 3]), 3, 1)\nfor i in range(len(cols_dd)):\n    fig.add_trace((piecharts[4 * i + 2]), 4, 1)\nfor i in range(len(cols_dd)):\n    fig.add_trace((piecharts[4 * i + 1]), 3, 2)\nfor i in range(len(cols_dd)):\n    fig.add_trace((piecharts[4 * i + 0]), 4, 2)\n    \n    \n#zoom in from world to berlin\nfig.update_geos(fitbounds=\"locations\", visible=False)\n\n\n#move subplot titles\nfig.layout.annotations[0].update(x=0.075)\nfig.layout.annotations[1].update(x=0.625)\nfig.layout.annotations[2].update(x=0.025)\nfig.layout.annotations[3].update(x=0.675)\n\n#update layout button style, size and subplot legend to be at the bottom\nfirst_title = cols_dd[0]\nfig.update_layout(dict(updatemenus=updatemenus), title=f\"<b>{first_title}</b>\",title_x=0.5, width=800,\n    height=900,\n    autosize=False,\n    legend=dict(\n        x=1,\n        y=0.5,\n        traceorder='normal',\n        font=dict(\n            size=12,),\n    ))\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Work in Progress...."}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}