How to bin longitude and latitude and plot the density of the bins?

Viewed 810

I am testing the code below.

import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
#plt.style.use('seaborn-white')


df = pd.read_csv('C:\\Users\\ryans\\OneDrive\\Desktop\\business.csv')
X = df[['latitude','longitude','address']].copy()

X['latitude'].value_counts()
X['longitude'].value_counts()

Result:

-115.123695    168
-111.940325    167
-115.171130    158
-111.821087    157
-115.224485    156

-82.032188       1
-89.383229       1
-89.533178       1
-81.475399       1
-111.857103      1

Next...

X['lat'] = pd.cut(df['latitude'], bins=10)
X['lon'] = pd.cut(df['longitude'], bins=10)
print(X)

Result:

         latitude   longitude  ...               lat                   lon
0       33.522143 -112.018481  ...  (33.187, 35.014]  (-115.536, -111.235]
1       43.605499  -79.652289  ...  (42.252, 44.062]     (-81.428, -77.17]
2       35.092564  -80.859132  ...  (35.014, 36.824]     (-81.428, -77.17]
3       33.455613 -112.395596  ...  (33.187, 35.014]  (-115.536, -111.235]
4       35.190012  -80.887223  ...  (35.014, 36.824]     (-81.428, -77.17]
          ...         ...  ...               ...                   ...
192604  36.213732 -115.177059  ...  (35.014, 36.824]  (-115.536, -111.235]
192605  44.052658  -79.481850  ...  (42.252, 44.062]     (-81.428, -77.17]
192606  33.679992 -112.035569  ...  (33.187, 35.014]  (-115.536, -111.235]
192607  33.416137 -111.735743  ...  (33.187, 35.014]  (-115.536, -111.235]
192608  36.107267 -115.171920  ...  (35.014, 36.824]  (-115.536, -111.235]

Now, I am trying to visualize these bins of coordinates, and plot the densities of bins. So, the higher the counts, the more intense the color. Is that possible?

I found a couple examples on line, which show how to create heat maps of longitude and latitude data. Is that the only to do it, or is it possible to bin these data points?

1 Answers

The following code does a pretty nice job!

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


df = pd.read_csv('C:\\your_path\\business.csv')
df.head(3)

max_amount = float(df['review_count'].max())

hmap = folium.Map(location=[42.5, -75.5], zoom_start=7, )

hm_wide = HeatMap( list(zip(df.latitude.values, df.longitude.values, df.review_count.values)),
                   min_opacity=0.2,
                   max_val=max_amount,
                   radius=17, blur=15, 
                   max_zoom=1, 
                 )

hmap.add_child(hm_wide)

enter image description here

enter image description here

I need to play with the opacity and the intensity of some of those colors, but the concept definitely makes sense.

Related