{"id":2093,"date":"2020-09-28T20:03:51","date_gmt":"2020-09-28T20:03:51","guid":{"rendered":"https:\/\/data-science.gotoauthority.com\/2020\/09\/28\/geographical-plots-with-python\/"},"modified":"2020-09-28T20:03:51","modified_gmt":"2020-09-28T20:03:51","slug":"geographical-plots-with-python","status":"publish","type":"post","link":"https:\/\/wealthrevelation.com\/data-science\/2020\/09\/28\/geographical-plots-with-python\/","title":{"rendered":"Geographical Plots with Python"},"content":{"rendered":"<div id=\"post-\">\n<p><b>By <a href=\"https:\/\/medium.com\/@ahmadbinshafiq\" target=\"_blank\" rel=\"noopener noreferrer\">Ahmad Bin Shafiq<\/a>, Machine Learning Student<\/b>.<\/p>\n<p><img class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/875\/0*oaVgFcI4bw_qX_H0\" width=\"90%\"><\/p>\n<p>\u00a0<\/p>\n<h3>Plotly<\/h3>\n<p>\u00a0<\/p>\n<blockquote>\n<p><em>Plotly is a famous library used for creating interactive plotting and dashboards in Python. Plotly is also a\u00a0<a href=\"https:\/\/plot.ly\/\" target=\"_blank\" rel=\"noopener noreferrer\">company<\/a>, that allows us to host both online and offline data visualisatoins.<\/em><\/p>\n<\/blockquote>\n<p>In this article, we will be using offline plotly to visually represent data in the form of different geographical maps.<\/p>\n<p><strong>Installing Plotly<\/strong><\/p>\n<div>\n<pre>pip install plotly\r\npip install cufflinks\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p>Run both commands in the command prompt to install\u00a0<strong>plotly<\/strong>\u00a0and\u00a0<strong>cufflinks\u00a0<\/strong>and all of their packages on our local machine.<\/p>\n<p><strong>Choropleth Map<\/strong><\/p>\n<blockquote>\n<p><em>Choropleth maps are popular thematic maps used to represent statistical data through various shading patterns or symbols on predetermined geographic areas (i.e., countries). They are good at utilizing data to easily represent the variability of the desired measurement across a region.<\/em><\/p>\n<\/blockquote>\n<p><strong>How does a Choropleth map works?<\/strong><\/p>\n<p>Choropleth Maps\u00a0display divided geographical areas or regions that are colored, shaded, or patterned in relation to a data variable. This provides a way to visualize values over a geographical area, which can show variation or patterns across the displayed location.<\/p>\n<p><strong>Using Choropleth with Python<\/strong><\/p>\n<p>Here, we will be using a\u00a0<a href=\"https:\/\/github.com\/ahmadbinshafiq\/Geographical-Plotting---Python\/blob\/master\/2014_World_Power_Consumption\" target=\"_blank\" rel=\"noopener noreferrer\">dataset<\/a>\u00a0of power consumption of different countries throughout the world in 2014.<\/p>\n<p>Okay, so let\u2019s get started.<\/p>\n<p><strong>Importing libraries<\/strong><\/p>\n<div>\n<pre>import plotly.graph_objs as go \r\nfrom plotly.offline import init_notebook_mode,iplot,plot\r\ninit_notebook_mode(connected=True)\r\n\r\nimport pandas as pd\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p>Here,\u00a0<em>init_notebook_mode(connected=True)<\/em>\u00a0connects Javascript to our notebook.<\/p>\n<p><strong>Creating\/Interpreting our DataFrame<\/strong><\/p>\n<div>\n<pre>df = pd.read_csv('2014_World_Power_Consumption')\r\ndf.info()\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><img class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/875\/1*6Qwcjl9xVbruR93IL7AEqw.png\" width='\"90%'><\/p>\n<p>Here we have 3 columns, and all of them have 219 non-null entries.<\/p>\n<p><img class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/875\/1*bB9bG0DtTzHR9ijsTMagxw.png\" width='\"90%'><\/p>\n<p><strong>Compiling our data into dictionaries<\/strong><\/p>\n<div>\n<pre>data = dict(\r\n        type = 'choropleth',\r\n        colorscale = 'Viridis',\r\n        locations = df['Country'],\r\n        locationmode = \"country names\",\r\n        z = df['Power Consumption KWH'],\r\n        text = df['Country'],\r\n        colorbar = {'title' : 'Power Consumption KWH'},\r\n      )\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><em>type = \u2019choropleth&#8217;<\/em>: defines the type of the map, i.e., choropleth in this case.<\/p>\n<p><em>colorscale = \u2018Viridis&#8217;<\/em>: displays a color map (f<em>or more color scales, refer\u00a0<\/em><a href=\"https:\/\/plotly.com\/python\/builtin-colorscales\/\" target=\"_blank\" rel=\"noopener noreferrer\"><em>here<\/em><\/a><em>).<\/em><\/p>\n<p><em>locations = df[&#8216;Country&#8217;]<\/em>: add a list of all countries.<\/p>\n<p><em>locationmode = &#8216;country names\u2019<\/em>: as we have country names in our dataset, so we set location mode to \u2018country names\u2019.<\/p>\n<p><em>z<\/em>: list of integer values that display the power consumption of each state.<\/p>\n<p><em>text = df[&#8216;Country&#8217;]<\/em>: displays a text when hovering over the map for each state element. In this case, it is the name of the country itself.<\/p>\n<p><em>colorbar = {\u2018title\u2019 : \u2018Power Consumption KWH\u2019}<\/em>: a dictionary that contains information about the right sidebar. Here, colorbar contains the title of the sidebar.<\/p>\n<div>\n<pre>layout = dict(title = '2014 Power Consumption KWH',\r\n              geo = dict(projection = {'type':'mercator'})\r\n             )\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<blockquote>\n<p><em>layout<\/em><em>\u00a0\u2014 <\/em>a\u00a0Geo object that can be used to control the appearance of the base\u00a0<strong>map<\/strong>\u00a0onto which data is plotted.<\/p>\n<\/blockquote>\n<p>It is a nested dictionary that contains all the relevant information about how our map\/plot should look like.<\/p>\n<p><strong>Generating our plot\/map<\/strong><\/p>\n<div>\n<pre>choromap = go.Figure(data = [data],layout = layout)\r\niplot(choromap,validate=False)\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><img class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/750\/1*ZgMv41WkdwV6AmEU_FTVTw.gif\" width=\"90%\"><\/p>\n<p>Cool! Our choropleth map for the \u20182014 World Power Consumption\u2019 has been generated, and from the above, we can see that each country displays its name and its power consumption in kWh when hovering over each element on the map. The more concentrated the data is in one particular area, the deeper the shade of color on the map. Here \u2018China\u2019 has the largest power consumption, and so its color is deepest.<\/p>\n<p>\u00a0<\/p>\n<h3>Density Maps<\/h3>\n<p>\u00a0<\/p>\n<p>Density mapping\u00a0is simply a way to show where points or lines may be concentrated in a given area.<\/p>\n<p><strong>Using Density Maps with Python<\/strong><\/p>\n<p>Here, we will be using a worldwide\u00a0<a href=\"https:\/\/raw.githubusercontent.com\/plotly\/datasets\/master\/earthquakes-23k.csv\" target=\"_blank\" rel=\"noopener noreferrer\">dataset<\/a>\u00a0of earthquakes and their magnitudes.<\/p>\n<p>Okay, so let\u2019s get started.<\/p>\n<p><strong>Importing libraries<\/strong><\/p>\n<div>\n<pre>import plotly.express as px\r\nimport pandas as pd\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><strong>Creating\/Interpreting our DataFrame<\/strong><\/p>\n<div>\n<pre>df = pd.read_csv('https:\/\/raw.githubusercontent.com\/plotly\/datasets\/master\/earthquakes-23k.csv')\r\ndf.info()\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><img loading=\"lazy\" class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/358\/1*2OlvyU2XiMy9DOqNsLK8Uw.png\" width=\"286\" height=\"147\"><\/p>\n<p>Here, we have 4 columns, and all of them have 23412 non-null entries.<\/p>\n<p>\u00a0<\/p>\n<p><img loading=\"lazy\" class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/379\/1*jXe45MJC6HAnIa5f_RIDsg.png\" width=\"303\" height=\"158\"><\/p>\n<p><strong>Plotting our data<\/strong><\/p>\n<div>\n<pre>fig = px.density_mapbox(df, lat='Latitude', lon='Longitude', z='Magnitude', radius=10,\r\n                        center=dict(lat=0, lon=180), zoom=0,\r\n                        mapbox_style=\"stamen-terrain\")\r\nfig.show()\r\n\r\n<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><em>lat=&#8217;Latitude&#8217;<\/em>: takes in the Latitude column of our data frame.<\/p>\n<p><em>lon=&#8217;Longitude&#8217;<\/em>: takes in the Longitude column of our data frame.<\/p>\n<p><em>z<\/em>: list of integer values that display the magnitude of the earthquake.<\/p>\n<p><em>radius=10<\/em>: sets the radius of influence of each point.<\/p>\n<p><em>center=dict(lat=0, lon=180)<\/em>: sets the center point of the map in a dictionary.<\/p>\n<p><em>zoom=0<\/em>: sets map zoom level.<\/p>\n<p><em>mapbox_style=&#8217;stamen-terrain&#8217;<\/em>: sets the base map style. Here, &#8220;stamen-terrain&#8221; is the base map style.<\/p>\n<p><em>fig.show()<\/em>: displays the map.<\/p>\n<p><strong>Map<\/strong><\/p>\n<p><img class=\"aligncenter size-large\" src=\"https:\/\/miro.medium.com\/max\/750\/1*sEF6PU3EzQMgFZlDQdjp4Q.gif\" width=\"90%\"><\/p>\n<p>Great! Our Density map for the \u2018Earthquakes and their magnitudes\u2019 has been generated, and from the above, we can see that it covers all the territories that suffered from the earthquake, and also shows the magnitude of the earthquake of every region when we\u00a0<strong>hover\u00a0<\/strong>over it.<\/p>\n<p>Geographical plotting using plotly can be a bit challenging sometimes due to its various formats of data, so please refer to this\u00a0<a href=\"https:\/\/images.plot.ly\/plotly-documentation\/images\/python_cheat_sheet.pdf\" target=\"_blank\" rel=\"noopener noreferrer\">cheat sheet<\/a>\u00a0for all types of syntaxes of\u00a0plotly\u00a0plots.<\/p>\n<p>\u00a0<\/p>\n<p>\u00a0<\/p>\n<p><b>Related:<\/b><\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>https:\/\/www.kdnuggets.com\/2020\/09\/geographical-plots-python.html<\/p>\n","protected":false},"author":0,"featured_media":2094,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[],"_links":{"self":[{"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/posts\/2093"}],"collection":[{"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/comments?post=2093"}],"version-history":[{"count":0,"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/posts\/2093\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/media\/2094"}],"wp:attachment":[{"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/media?parent=2093"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/categories?post=2093"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wealthrevelation.com\/data-science\/wp-json\/wp\/v2\/tags?post=2093"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}