利用python画地区热力图

mport requests
import json
import re
import numpy as np
import pandas as pd

#做数据预处理,将数据调整为xx省xx市xx
df=pd.read_excel('嘉定.xlsx')
place=df['设备描述']
place1=[]
for i in place:
    place1.append('上海市嘉定区安亭镇'+i)

#利用百度api获取地区的经纬度
AK = 'PmbFA5jwHSpwMRkumX6CpAtUWGqusswc'
jingdu=[]
weidu=[]
zhi=[]
for address in place1:
    url = 'http://api.map.baidu.com/geocoding/v3/?address={}&output=json&ak={}&callback=showLocation'.format(address,AK)
    res = requests.get(url)
    print(res.text)
    results = json.loads(re.findall(r'\((.*?)\)',res.text)[0])
    print('\n')
    jingdu.append(results['result']['location']['lng'])
    weidu.append(results['result']['location']['lat'])
    zhi.append(results['result']['location'])
    print('location is ',results['result']['location'])
jieguo=pd.DataFrame({'地址':place1,'经度':jingdu,'纬度':weidu})
jieguo.to_excel('值.xlsx')


from pyecharts.charts import Geo
from pyecharts import options as opts
from pyecharts.globals import GeoType


def test_geo():
    city = '上海'
    g = Geo(init_opts=opts.InitOpts(width='1350px', height='750px'))
    g.add_schema(maptype=city)

    # 定义坐标对应的名称,添加到坐标库中 add_coordinate(name, lng, lat)
    for i in range(len(jingdu)):
        g.add_coordinate(place1[i],jingdu[i],weidu[i])

    # 定义数据对,
    #data_pair = [('湖南省长沙市雨花区跳马镇仙峰岭', 10), ('湖南省长沙市宁乡市横市镇藕塘', 5), ('湖南省长沙市长沙县黄花镇新塘铺长沙黄花国际机场', 20)]
    data_pair=[]
    for i in jieguo['地址']:
        data_pair.append((i,1))
    # Geo 图类型,有 scatter, effectScatter, heatmap, lines 4 种,建议使用
    # from pyecharts.globals import GeoType
    # GeoType.GeoType.EFFECT_SCATTER,GeoType.HEATMAP,GeoType.LINES

    # 将数据添加到地图上
    g.add('',data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=5)
    # 设置样式
    g.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    # 自定义分段 color 可以用取色器取色

#不同的数量可选用不同的颜色
    #pieces = [
    #     {'max': 1, 'label': '0以下', 'color': '#50A3BA'},
    #     {'min': 1, 'max': 10, 'label': '1-10', 'color': 'red'},
    #     {'min': 10, 'max': 20, 'label': '10-20', 'color': '#81AE9F'},
    #     {'min': 20, 'max': 30, 'label': '20-30', 'color': '#E2C568'},
    #     {'min': 30, 'max': 50, 'label': '30-50', 'color': '#FCF84D'},
    #     {'min': 50, 'max': 100, 'label': '50-100', 'color': '#DD0200'},
    #     {'min': 100, 'max': 200, 'label': '100-200', 'color': '#DD675E'},
    #     {'min': 200, 'label': '200以上', 'color': '#D94E5D'}  # 有下限无上限
    # ]

#因为我的数据每条数据都是唯一的,所以只设一个颜色。
    pieces = [
        {'min': 1, 'max':10, 'label': '1', 'color': 'red'},
        
    ]
    #  is_piecewise 是否自定义分段, 变为true 才能生效
    g.set_global_opts(
        visualmap_opts=opts.VisualMapOpts(is_piecewise=True, pieces=pieces),
        title_opts=opts.TitleOpts(title="{}嘉定分布".format(city)),
    )
    return g

g = test_geo()
# 渲染成html, 可用浏览器直接打开
g.render('test_render2.html')

你可能感兴趣的:(python,开发语言,数据分析)