Skip to main content

Making a Geographic Heatmap with Python

     We have a requirement like need to create a map where user is traveled.There are many libraries available in python to draw a map if you have list of co-ordinates with you like(longitude and latitude) 

To name few packages : vincent, bokeh, plot.ly and matplotlib and folium

 


Things to consider while choosing the library:

1. Open source

2. Painless to use

3. built in support for heat-maps

4. actively maintained

Folium is the lib which will satisfy above all use cases

Requirements:

pip install folium

pip install geopands (for adding other geo json files)

pip install pands (to read csv of excel files which are having the co-ordinates data)

Creating the map:

import pandas as pd 
import folium
from folium.plugins import HeatMapmap_df = pd.read_csv('map.csv', sep='\t')max_amount = float(map_df['Amount'].max())hmap = folium.Map(location=[42.5, -75.5], zoom_start=7, )hm_wide = HeatMap( list(zip(map_df.lat.values, 
            map_df.lon.values, map_df.Amount.values)),
min_opacity=0.2,
max_val=max_amount,
radius=17, blur=15,
max_zoom=1,
)folium.GeoJson(district23).add_to(hmap)
hmap.add_child(hm_wide)
 

 Save map as html:

        hmap.save(os.path.join('results', 'map.html'))

Export it as PNG/JPEG:

 1. Using with xvfb with cutycapt

 2. Using Selenium web driver

 

Cutycapt:

    Install the package using the apt-get cutycapt

    sudo apt-get install cutycapt

    sudo apt-get install xvfb

 

Python code:

import os
import subprocess
outdir = "screenshots" # this directory has to exist..
map.save("tmp.html")
url = "file://{}/tmp.html".format(os.getcwd())
outfn = os.path.join(outdir,"outfig.png")
subprocess.check_call(["cutycapt","--url={}".format(url), "--out={}".format(outfn)])

 Selenium Webdriver:

import os
import time
from selenium import webdriverfn='testmap.html'
tmpurl='file://{path}/{mapfile}'.format(path=os.getcwd(),mapfile=fn)
folium_map.save(fn)browser = webdriver.Firefox()
browser.get(tmpurl)
time.sleep(5) #Give the map tiles some time to load
browser.save_screenshot('map.png')
browser.quit()

Comments

  1. in above code "folium.GeoJson(district23).add_to(hmap)" written for creating heatmap.
    what it defines code? i have five columns sample data with columns name,latitude,longitude. i written with the help of above code i struck on that code..pls help me on this issue .with out this line(folium.GeoJson(district23).add_to(hmap)
    ) i run but i am not getting map and it is not shown error, but not getting map

    ReplyDelete
  2. Name latitude longitude
    Ram 30.02096 -95.52322
    Venkat 30.27043056 -97.75386111
    Vijay 30.2452 -97.75751
    Nitesh 30.29370998 -97.74172805
    Chinna 30.26416385 -97.74061482
    Prakash 30.268975 -97.72871389
    this is my sample data

    import pandas as pd
    import folium
    from folium.plugins import HeatMap

    df = pd.read_csv(r'C:\Users\Ramu\Desktop\python csv.csv')

    hmap = folium.Map(location=[30.169621,-96.683617], zoom_start=8,)

    hm_wide = HeatMap(
    list(zip(df.latitude.values, df.longitude.values)),

    min_opacity=0.3,
    radius=15,
    blur=10,
    max_zoom=2,
    )
    folium.Geocsv(latitude).add_to(hmap)
    hmap.add_child(hm_wide)

    if i run this code i am getting error-

    ===================== RESTART: C:\Users\Ramu\Desktop\new.py ====================
    Traceback (most recent call last):
    File "C:\Users\Ramu\Desktop\new.py", line 20, in
    folium.Geocsv(latitude).add_to(hmap)
    AttributeError: module 'folium' has no attribute 'Geocsv'

    without this line code "folium.Geocsv(latitude).add_to(hmap)" i am not getting any error but map was not shown...
    please help me on this issue, it is very important for me.
    thanks

    ReplyDelete

Post a Comment

Popular posts from this blog

CommandLine Args In Python

 Command line args in Python :      When the program comes to Python , it's all about libraries .Argparser is the library used for the taking inputs from the command line. Here you can validate the arguments which are entered by the user without writing the another function to validate from the if conditions. suppose give a filename like cmdprocess.py You can give the expecting arguments like below cmdprocess.py --help      it will give the total arguments with respective commands to represent Required =True :           When the required is true. You have to enter the argument.   Type = function name:          Type is very useful to validate the input entered by the user. so that you can send a message like user need to enter the defined arguments only. This function always expects the input argument . Custom-Exceptions In Python:    There are multiple exception...

ReplicaSet In Mongodb

Replica Set      A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Creating the mongod instances: First we need to create a mongod isntance using below command. before creating the instance make a directory with any name ex: db1 and give this path in the below command Use any port you want  mongod --port 20017 --dbpath C:\Users\michel\db1\ --replSet rs0 Create a another mongod isntance using the different terminal by using the same command but give different path and port number is diffferent mongod --port 20018 --dbpath C:\Users\michel\db2\ --replSet rs0 Creating the mongo shell terminals: Now use the new terminal to open mongo terminal using below command mongo --port 20017 then initiate the replica set using be...