Пример #1
0
def geo():
    g = Geo(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION))
    g.add_schema(maptype='广州')

    # 定义坐标对应的名称,添加到坐标库中 add_coordinate(name, lng, lat)
    names = list(df['店铺名称'])
    lng = list(df['经度'])
    lat = list(df['纬度'])
    for i in range(len(names)):
        g.add_coordinate(names[i], lng[i], lat[i])

    # 定义数据对,
    data_pair = [(name, 50) for name in names]

    # 将数据添加到地图上
    g.add('', data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=3)

    # 设置样式
    g.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    g.set_global_opts(
        visualmap_opts=opts.VisualMapOpts(is_show=False),
        title_opts=opts.TitleOpts(title="广州美食分布"),
    )
    g.render('广州美食分布.html')
    return g
Пример #2
0
def task():
    city = '北京'
    g = Geo(init_opts=opts.InitOpts(width = '1600px', height='800px'))
    g.add_schema(maptype=city)

    # 数据库连接
    db = pymysql.connect(host = 'localhost', user='******', password='******', port=3306, db = 'educationalResource_bj')
    cursor = db.cursor()
    sql = 'select * from educationalResourceMap'
    cursor.execute(sql)
    results = cursor.fetchall()
    db.close()
    #print(results[0][1])

    for result in results:
        g.add_coordinate(result[1], result[6], result[7])

    data_pair = []
    for result in results:
        judge = 0
        if result[3] == 'gbyey':
            judge = 10
        elif result[3] == 'xx':
            judge = 20
        elif result[3] == 'zx':
            judge = 30
        elif result[3] == 'zyjyxx':
            judge = 50
        elif result[3] == 'gdyx':
            judge = 80
        else :
            judge = 101
        data_pair.append((result[1], judge))

    #print(data_pair)

    # 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 = [
        {'min': 1, 'max': 10, 'label': '幼儿园', 'color': '#3700A4'},
        {'min': 10, 'max': 20, 'label': '小学', 'color': '#81AE9F'},
        {'min': 20, 'max': 30, 'label': '中学', 'color': '#E2C568'},
        {'min': 30, 'max': 50, 'label': '职业技术学校', 'color': '#FCF84D'},
        {'min': 50, 'max': 100, 'label': '高等院校', 'color': '#DD0200'},
        {'min': 100, 'max': 200, 'label': '特殊教育学校', 'color': '#DD675E'},
    ]
    #  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
Пример #3
0
def func3(path="temp.csv"):
    win = tkinter.Tk()
    x = win.winfo_screenwidth()
    y = win.winfo_screenheight()

    pieces = [
        {
            'min': 0,
            'max': 0,
            'label': '数据无效',
            'color': '#00B2EE'
        },
        {
            'min': 1,
            'max': 1,
            'label': '数据疑似为假',
            'color': '#71C671'
        },
        {
            'min': 2,
            'max': 2,
            'label': '数据疑似为真',
            'color': '#CD4F39'
        },
    ]

    data = pd.read_csv(path)  # 读取数据

    geo_sight_coord = data[['dx', 'dy']]  # 构造位置字典数据
    # data_pair = [(str(i), 1) for i in range(len(geo_sight_coord))]  # 构造项目租金数据
    data_pair = []
    for index, row in data.iterrows():
        data_pair.append((str(index), int(row['flag_legal'])))

    g = Geo(init_opts=opts.InitOpts(
        page_title="车辆轨迹",
        width=str(x / 1.1) + 'px',
        height=str(y / 1.1) + 'px',
    ))  # 地理初始化

    g.add_schema(maptype="江西")  # 限定上海市范围
    for key, value in geo_sight_coord.iterrows():  # 对地理点循环
        g.add_coordinate(str(key), value['dx'], value['dy'])  # 追加点位置

    g.add("", data_pair, symbol_size=4)  # 追加项目名称和租金
    g.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),
        type='scatter',
    )  # 星散点图scatter

    g.set_global_opts(visualmap_opts=opts.VisualMapOpts(
        is_piecewise=True,
        pieces=pieces,
        pos_left='left',
        pos_bottom="100px",
    ),
                      title_opts=opts.TitleOpts(title="车辆轨迹"))
    g.render(path="车辆加油地图.html")
Пример #4
0
def locate_on_map(addr, longtitude, latitude):
    g = Geo().add_schema(maptype="上海")
    g.add_coordinate(addr, longtitude, latitude)
    data_pair = [(addr, 1)]
    g.add('', data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=20)
    g.set_series_opts(label_opts=options.LabelOpts(is_show=False))
    g.set_global_opts(title_opts=options.TitleOpts(title="地图标点测试"))

    g.render_notebook()
    print("process finished")
Пример #5
0
def quakes():
    # 对地震数据进行绘图
    quakes_data = pd.read_csv("quakes.csv")
    latitude = quakes_data['lat'].values
    longitude = quakes_data['long'].values
    mag = quakes_data['mag'].values
    index = list(range(len(mag)))

    #可视化
    geo = Geo()
    geo.add_schema(maptype='world')
    for i in range(len(index)):
        geo.add_coordinate(index[i], longitude[i], latitude[i])

    data_pair = [list(z) for z in zip(index, mag)]
    # 将数据添加进图中
    geo.add('震源', data_pair, symbol_size=3)
    geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    # 设置显示区间
    pieces = [
        {
            'max': 4,
            'label': '4级以下',
            'color': '#50A3BA'
        },
        {
            'min': 4,
            'max': 5,
            'label': '4-5级',
            'color': '#E2C568'
        },
        {
            'min': 5,
            'max': 6,
            'label': '5-6级',
            'color': '#D94E5D'
        },
        {
            'min': 6,
            'max': 7,
            'label': '6-7级',
            'color': '#3700A4'
        },
        {
            'min': 7,
            'label': '7级以上',
            'color': '#81AE9F'
        },
    ]
    geo.set_global_opts(visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                          pieces=pieces),
                        title_opts=opts.TitleOpts(title="震源分布"))
    #导出图像
    geo.render('地震地点分布.html')
Пример #6
0
def drawGeoMap(excel_path, mtype='china'):
    data = xlrd.open_workbook(excel_path)
    table = data.sheet_by_index(0)
    nrow = table.nrows
    dates = table.row_values(0)
    # print(dates)
    allData = {}
    for i in range(1, nrow):
        aNameData = {}
        sname = f"{table.cell(i,0).value} {table.cell(i,1).value}"
        for j in range(2, len(dates)):
            value = table.cell(i,j).value
            try:
                value = json.loads(value)
                value = value[1:4]
            except Exception as e:
                print(f"error: {e}")
                pass
            aNameData[dates[j]] = value
        allData[sname] = aNameData

    # print(f'学生数:{len(allData)}')

    title = '2021年1月21日能仔位置'
    geo = Geo(init_opts=opts.InitOpts(width='1000px', height='580px', page_title=title, theme=ThemeType.LIGHT))

    geo.add_schema(maptype=mtype)

    for name, data in allData.items():
        for date, location in data.items():
            aNameLocation = []
            try:
                longitude, latitude, address = location
            except Exception as e:
                print(f"Error: {e}")
                longitude, latitude, address = DEFAULT_Location
            # aNameLocation.append(('%s %s\n' % (name, date), address))
            # geo.add_coordinate('%s %s' % (name, date), longitude, latitude)
            sno, sname = name.split(' ')
            # print(sno, sname)
            aNameLocation.append(('%s %s' % (sno, sname), date))
            geo.add_coordinate('%s %s' % (sno, sname), longitude, latitude)
            geo.add(name, aNameLocation, type_=ChartType.EFFECT_SCATTER)

    geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    geo.set_global_opts(legend_opts=opts.LegendOpts(type_='scroll', orient='vertical', pos_left='left', pos_top='10%', is_show=False), title_opts=opts.TitleOpts(title=title))

    map_path = os.path.join(dir_path, '2021年1月21日能仔位置地图.html')
    geo.render(map_path)

    # os.system(f'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" {os.path.abspath(map_path)}')

    print('done.')
Пример #7
0
def draw_map(data_pair, data_coordinate) -> Geo:   # ->常常出现在python函数定义的函数名后面,为函数添加元数据,描述函数的返回类型,从而方便开发人员使用。
    g = Geo()
    # 选择要显示的地图
    g.add_schema(maptype="重庆", center=[106.531638,29.561081], itemstyle_opts=opts.ItemStyleOpts(color="#575D57"))
    # 使用add_coordinate(name, lng, lat)添加坐标点和坐标名称
    for item in data_coordinate:
        g.add_coordinate(item['name'], item['lng'], item['lat'])
    # 将数据添加到定义的地图上
    g.add('', data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=5)                         # type_=ChartType.HEATMAP
    # 设置样式
    g.set_series_opts(label_opts=opts.LabelOpts(is_show=False))\
                                     .set_global_opts(visualmap_opts=opts.VisualMapOpts(min_=60, max_ = 200, is_piecewise=True),title_opts=opts.TitleOpts(title="重庆房源分布图"))
    return g
Пример #8
0
def insert_loc():
    g = Geo()
    data_pair = []
    g.add_schema(maptype='china')
    airport_df = pd.read_excel('CN_airport_info.xlsx', usecols='B,D,E,F,S')
    for i in range(len(airport_df)):
        g.add_coordinate(airport_df.iloc[i, 1], float(airport_df.iloc[i, 3]),
                         float(airport_df.iloc[i, 2]))
        data_pair.append((airport_df.iloc[i, 1], int(airport_df.iloc[i, 4])))
    g.add('', data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=7)
    g.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    g.set_global_opts(
        visualmap_opts=opts.VisualMapOpts(is_piecewise=False),
        title_opts=opts.TitleOpts(title="全国机场分布图"),
    )
    return g
Пример #9
0
def plot_geolines(plotting_data, geo_cities_coords):
    c = Geo(init_opts=opts.InitOpts(width='1500px', height='700px'))
    c.add_schema(
        maptype="china",
        itemstyle_opts=opts.ItemStyleOpts(color="#F0CA00", border_color="#111"))
    # 所有坐标点加进地图
    for i in range(0, len(geo_cities_coords)):
        c.add_coordinate(list(geo_cities_coords.keys())[i], list(geo_cities_coords.values())[i][0],
                         list(geo_cities_coords.values())[i][1])
    c.add('仓网结构', plotting_data,
          type_=GeoType.LINES,
          linestyle_opts=opts.LineStyleOpts(width=1),
          label_opts=opts.LabelOpts(is_show=False),
          ##trail_length=0,
          is_polyline=True)
    c.set_global_opts(title_opts=opts.TitleOpts(title="仓网结构"))
    c.render('二级仓网结构.html')
Пример #10
0
def draw_with_echarts_scatter():
    '''使用pyecharts画散点图'''
    try:
        device_csv_dir = r'E:/test_opencv/车辆经常停留位置/all_device_data_csv/'
        pyecharts_device_html_dir = r'E:/test_opencv/车辆经常停留位置/pyecharts_device_html/'
        if not os.path.exists(device_csv_dir):
            os.makedirs(device_csv_dir)
        if not os.path.exists(pyecharts_device_html_dir):
            os.makedirs(pyecharts_device_html_dir)
        for item in os.listdir(device_csv_dir):
            csvlName = device_csv_dir + item
            df = pd.read_csv(csvlName, encoding='utf-8', low_memory=False)
            # X = df.drop_duplicates(subset=['longitude', 'latitude'])
            X = df
            device_id = X['device_id'].iloc[0]  # 取组内第一个device_id用于存csv用
            staff_id = X['staff_id'].iloc[0]  # 取组内第一个staff_id用于存csv用
            staff_name = X['staff_name'].iloc[0]  # 取组内第一个staff_name用于存csv用
            car_id = X['car_id'].iloc[0]  # 取组内第一个car_id用于存csv用
            car_num = X['car_num'].iloc[0]  # 取组内第一个car_num用于存csv用
            create_time_1 = X['create_time_1'].iloc[0]  # 取组内第一个create_time_1用于存csv用
            g = Geo()
            g.add_schema(maptype="china")
            # 给所有点附上标签 'create_time'
            for index, row in X.iterrows():
                g.add_coordinate(row['create_time'], row['remain_longitude'], row['remain_latitude'])
            create_time = X.create_time.values.tolist()
            # 给每个点的值赋为 1
            data_list = [[item, 1] for item in create_time]
            # 画图
            # g.add('', data_list, type_=GeoType.HEATMAP, symbol_size=2)
            g.add('', data_list, type_=GeoType.EFFECT_SCATTER, symbol_size=2)
            g.set_series_opts(label_opts=options.LabelOpts(is_show=False))
            #heatmap
            # g.set_global_opts(visualmap_opts=options.VisualMapOpts(), title_opts=options.TitleOpts(title=staff_name+"_" + str(car_num) + '_' + str(create_time_1) +'_heatmap'  ,pos_left='50%',pos_top='20'))
            #scatter
            g.set_global_opts(title_opts=options.TitleOpts(title=staff_name+"_" + str(car_num) + '_' + str(create_time_1) +'_scatter'  ,pos_left='50%',pos_top='20'))
            # 保存结果到 html
            result = g.render(pyecharts_device_html_dir +  str(staff_name) + '_' +str(car_num) + '_' + str(create_time_1) + '.html')

    except Exception as ex:
        logger.error("Call method draw_with_echarts_scatter() error!")
        logger.error("Exception:" + str(ex))
        raise ex
Пример #11
0
 def get_geo_base(self, _data):
     '''
     plot geo-HeatMap
     :param _data: gps对应的城市分布(dataframe)
     :return: geo城市分布图
     '''
     register_url(self.echarts_url)
     geo = Geo(init_opts=opts.InitOpts(width="1000px",
                                       height="600px",
                                       page_title=self.country,
                                       bg_color=''))
     geo.add_schema(maptype=self.country)
     for _city, _gps in self.geo_dict.items():
         geo.add_coordinate(name=_city, longitude=_gps[0], latitude=_gps[1])
     geo.add(series_name=self.series_name,
             data_pair=_data,
             type_=ChartType.HEATMAP)
     geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
     geo.set_global_opts(
         visualmap_opts=opts.VisualMapOpts(max_=self.threshold_plot),
         title_opts=opts.TitleOpts(title="Geo-HeatMap"))
     return geo
Пример #12
0
class NetworkVisualization(object):
    """
    class which show the demand heat map and the allocation network
    """
    def __init__(self, data_class, json_file=None):
        """
        Initialization the class with data_class and json_file parameters, and add the customized city into Geo class
        :param data_class: the data_class
        :param json_file:
        """
        self.geo = Geo()
        self.data_class = data_class
        self.json_file = json_file
        if self.json_file is not None:
            self._load_coordinate_json()
        else:
            if not hasattr(self.data_class, 'city'):
                raise ValueError(
                    'the city and corresponding longitude and latitude should be included in data_class!'
                )
            else:
                self._load_coordinate()

    def _load_coordinate(self):
        # add the customized city with the corresponding longitude and latitude
        if len(self.data_class.city) != len(self.data_class.longitude):
            raise ValueError(
                'the length of city and longitude and latitude should be same !'
            )
        for city, longitude, latitude in zip(self.data_class.city,
                                             self.data_class.longitude,
                                             self.data_class.latitude):
            self.geo.add_coordinate(city, longitude, latitude)

    def _load_coordinate_json(self):
        # add the customized city with the longitude and latitude json file to Geo
        # json file contents: { 'city name':[120.123,32.345] }
        self.geo.add_coordinate_json(self.json_file)

    def heat_map(self, city, demand) -> Geo:
        c = (Geo().add_schema(maptype="china").add(
            "demand heat map ", [list(z) for z in zip(city, demand)],
            type_=ChartType.HEATMAP,
            symbol_size=8).set_series_opts(label_opts=opts.LabelOpts(
                is_show=False)).set_global_opts(
                    visualmap_opts=opts.VisualMapOpts(max_=max(demand) * 1.2),
                    title_opts=opts.TitleOpts(title="demand heat map "),
                ))
        return c

    def net_work_map(self, source_list, cost, destination_list, demand, source,
                     destination) -> Geo:
        """
        output the network map based on the source and destination pair.
        :param source_list: the unique source list
        :param cost: the cost of source list
        :param destination_list: the unique destination list
        :param demand: the demand of destination
        :param source: the all source point
        :param destination: the all destination point
        :return:
        """
        c = (
            Geo().add_schema(maptype="china").add(
                "", [z for z in zip(source_list, cost)],
                type_=ChartType.SCATTER,
                color='green',
                symbol_size=5,
                symbol="image://..\\icon\\warehouse_1.png").add(
                    "",
                    [z for z in zip(destination_list, demand)],
                    type_=ChartType.SCATTER,
                    color='black',
                    symbol_size=5,
                    # symbol="image://..\\icon\\customer.png"
                ).add(
                    "Network",
                    [list(z) for z in zip(source, destination)],
                    type_=ChartType.LINES,
                    symbol=[None, 'arrow'],
                    symbol_size=3,
                    effect_opts=opts.EffectOpts(
                        period=20,
                        scale=1,
                        symbol="image://..\\icon\\car.png",
                        symbol_size=15,
                        color="blue",
                        trail_length=0),
                    linestyle_opts=opts.LineStyleOpts(curve=0.1, opacity=0.3),
                ).set_series_opts(label_opts=opts.LabelOpts(
                    is_show=False)).set_global_opts(
                        title_opts=opts.TitleOpts(title="Allocation Network"),
                        visualmap_opts=opts.VisualMapOpts(is_piecewise=False,
                                                          max_=max(demand),
                                                          type_='size',
                                                          range_size=[10,
                                                                      20])))
        return c
Пример #13
0
    def networkcivilisation(self):
        """
        画出仓网覆盖现状
        """
        # 获取RDC仓位置和城市经纬度坐标点
        RDC_cords = {self.GIS[rdc]['city_name_cn'].split("市")[0] + '仓' : (self.GIS[rdc]['lng'], self.GIS[rdc]['lat']) \
                for rdc in self.rdc}
        City_cords = {
            customer: (self.GIS[customer]['lng'], self.GIS[customer]['lat'])
            for customer in self.customer
        }

        # 初始化地图
        c = Geo(init_opts=opts.InitOpts(width='1500px', height='700px'))
        c.add_schema(maptype="china",
                     itemstyle_opts=opts.ItemStyleOpts(color="#F0CA00",
                                                       border_color="#111"))

        # 所有城市、RDC仓的坐标加进地图中
        for key, value in RDC_cords.items():
            c.add_coordinate(key, value[0], value[1])
        for key, value in City_cords.items():
            c.add_coordinate(key, value[0], value[1])

        # 地图中加RDC仓的点
        c.add("RDC仓",
              [[z,1] for z in RDC_cords.keys()],
              type_="scatter", label_opts=opts.LabelOpts(formatter="{b}", color='red', font_size=16, font_weight='bold',\
                                                         position = 'right')
              , color='#3481B8', symbol='pin',
              # 标记图形形状,circle,pin,rect,diamon,roundRect,arrow,triangle
              symbol_size=16
              )

        #加需求点
        non_rdc_customer = set(self.customer) - set(self.rdc)
        c.add("需求点", [[z, 1] for z in non_rdc_customer],
              type_="scatter",
              label_opts=opts.LabelOpts(is_show=False),
              color='blue',
              blur_size=1,
              symbol_size=5)

        # 循环添加每一个覆盖
        colors = [
            "#F70000", "#373F43", "#0A0A0D", "#3E753B", "#3481B8", "#904684",
            "#D47479", "#a21c68", "#e38105", "#42d1bd"
        ]
        m = 0
        for rdc in self.rdc:
            flow = []
            for key, value in self.demand.items():
                if key[0] == rdc:
                    flow.append((key[0], key[1]))
            c.add(
                series_name=self.GIS[rdc]['city_name_cn'].split('市')[0] + '仓',
                data_pair=flow,
                type_=GeoType.LINES,
                linestyle_opts=opts.LineStyleOpts(width=0.8, color=colors[m]),
                label_opts=opts.LabelOpts(is_show=False),
                ##trail_length=0,
                is_polyline=True)
            m += 1

        c.set_global_opts(title_opts=opts.TitleOpts(title="现状仓网覆盖"))
        c.render("现状仓网覆盖.html")
Пример #14
0
from pyecharts.charts import Geo
from pyecharts.globals import ChartType
from pyecharts import options as opts
# bar = Bar()
# bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
# bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,如 bar.render("mycharts.html")
# bar.render()

citys = ['丰县', '沛县', '铜山区', '贾汪区', '鼓楼区', '泉山区', '云龙区', '邳州市', '新沂市', '睢宁县']
values = [120, 160, 180, 200, 180, 190, 130, 160, 140, 170]
geo = Geo()
geo.add_schema(maptype="徐州")
geo.add_coordinate("某地", 117.3, 34.3)
print([list(z) for z in zip(citys, values)])
geo.add("test", [list(z) for z in zip(citys, values)],
        type_=ChartType.EFFECT_SCATTER)
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
geo.set_global_opts(visualmap_opts=opts.VisualMapOpts(),
                    title_opts=opts.TitleOpts(title="Geo地图示例"))
geo.render("测试.html")
Пример #15
0
    gys_unuse_df['CDC_Name'].isna())].drop_duplicates()['城市代码']

# 初始化地图
c = Geo(init_opts=opts.InitOpts(width='1200px', height='700px'))
c.add_schema(maptype="china",
             itemstyle_opts=opts.ItemStyleOpts(color="#F0CA00",
                                               border_color="#111"))

# CDC位置加入地图坐标
CDC_cords = {
    GIS[gys_total.iloc[i]['城市代码']]['city_name_cn']:
    (gys_total.iloc[i]['CDC_LGT'], gys_total.iloc[i]['CDC_LAT'])
    for i in range(len(gys_total))
}  ##会自动去重
for key, value in CDC_cords.items():
    c.add_coordinate(key, value[0], value[1])

# 未被选择的CDC加入地图坐标
unuse_cdc_sku = {'763':'包装胶袋','746':'包装胶袋','754':'包装胶袋','591':'防护用品,封箱胶纸,配饰用品,称重工具,贴纸类',\
                   '553':'称重工具','762':'封条类','532':'封条类','577':'封条类,一次性编织袋','592':'封箱胶纸',\
                   '535':'配饰用品','631':'夏装','756':'配饰用品,贴纸类,纸质运单'}
unuse_cdc_cords = {GIS[key]['city_name_cn'] + ':' + value : (GIS[key]['lng'], GIS[key]['lat']) \
                   for key,value in unuse_cdc_sku.items()}
for key, value in unuse_cdc_cords.items():
    c.add_coordinate(key, value[0], value[1])

# RDC位置加入地图坐标
RDC_cords = {GIS[gys_rdc.iloc[i]['RDC_Name']]['city_name_cn'].split('市')[0] + '仓': [gys_rdc.iloc[i]['RDC_LGT'],\
             gys_rdc.iloc[i]['RDC_LAT']] for i in range(len(gys_rdc))}  ##会自动去重
for key, value in RDC_cords.items():
    c.add_coordinate(key, value[0], value[1])
Пример #16
0
def geo():
    place_avaliable = passenger_spider(None, all=True)
    place_no_weather = passenger_spider_no_weather()
    city = '上海'
    g = Geo(init_opts=opts.InitOpts(
        width="100%", height="100%", bg_color="#12406d"))
    g.add_schema(maptype=city,
                 itemstyle_opts=opts.ItemStyleOpts(color="#135dbe",
                                                   border_color="#fff"),
                 zoom=1.2)
    # 定义坐标对应的名称,添加到坐标库中 add_coordinate(name, lng, lat)
    for k, v in jingwei_dict.items():
        g.add_coordinate(k, float(v[1]), float(v[0]))
    for item in place_no_weather:
        g.add_coordinate(item["NAME"], float(item["LOCATION_X"]),
                         float(item["LOCATION_Y"]))

    coordinates = []
    for k in jingwei_dict.keys():
        data_pairs = []
        data_pairs.append(k)
        for p in place_avaliable:
            if k == p["NAME"]:
                if not p.get("MAX_NUM"):
                    data_pairs.append(0.0)
                else:
                    data_pairs.append(
                        round(int(p["NUM"]) / int(p["MAX_NUM"]), 2))
                break
        if len(data_pairs) == 1:
            data_pairs.append(0.0)
        data_pairs = tuple(data_pairs)
        coordinates.append(data_pairs)

    for item in place_no_weather:
        data_pairs = []
        data_pairs.append(item["NAME"])
        if (not item["MAX_NUM"]) or (item["MAX_NUM"] == ""):
            data_pairs.append(0)
        else:
            data_pairs.append(round(
                int(item["NUM"]) / int(item["MAX_NUM"]), 2))
        data_pairs = tuple(data_pairs)
        coordinates.append(data_pairs)

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

    # 将数据添加到地图上
    g.add('', data_pair, type_=ChartType.EFFECT_SCATTER)
    # 设置样式
    g.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False, formatter="{b}:{c}"))
    # 自定义分段 color 可以用取色器取色
    pieces = [
        {
            'max': 0.1,
            'label': '10%以下',
            'color': '#98F5FF'
        },
        {
            'min': 0.1,
            'max': 0.3,
            'label': '10%-30%',
            'color': '#0f0'
        },
        {
            'min': 0.3,
            'max': 0.5,
            'label': '30%-50%',
            'color': 'orange'
        },
        {
            'min': 0.5,
            'max': 0.7,
            'label': '50%-70%',
            'color': '#E2C568'
        },
        {
            'min': 0.7,
            'max': 0.8,
            'label': '70%-80%',
            'color': '#FCF84D'
        },
        {
            'min': 0.8,
            'max': 0.9,
            'label': '80%-90%',
            'color': '#3700A4'
        },
        {
            'min': 0.9,
            'max': 1,
            'label': '90%-100%',
            'color': '#DD675E'
        },
        {
            'min': 1,
            'label': '100%以上',
            'color': '#f00'
        }  # 有下限无上限
    ]
    #  is_piecewise 是否自定义分段, 变为true 才能生效
    g.set_global_opts(
        visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                          pieces=pieces,
                                          textstyle_opts=opts.TextStyleOpts(
                                              color="#fff")))
    return g
Пример #17
0
    center=[116.46, 39.92],
    zoom=3,
    itemstyle_opts=opts.ItemStyleOpts(color="#fff",
                                      border_width=1,
                                      border_color="#1E90FF"),
    emphasis_label_opts=opts.LabelOpts(is_show=False),
    emphasis_itemstyle_opts=opts.ItemStyleOpts(color="#FFFACD"),
    label_opts=opts.LabelOpts(is_show=True,
                              font_size=16,
                              font_style='italic',
                              color='#1E90FF'),
)

stations = []
for idx, row in df.iterrows():
    geo.add_coordinate(row['站点名称'], row['经度'], row['纬度'])
    stations.append([row['站点名称'], 1])

for line in lines:
    # 线图
    geo.add(
        line,
        # 数据格式(from, to)
        data_pair=line,
        type_='lines',
        label_opts=opts.LabelOpts(is_show=False),
        symbol_size=8,
        symbol='emptyCircle',
        is_polyline=False,
        linestyle_opts=line_style,
        effect_opts={
Пример #18
0
    'geo',
    prov_tuple,
).set_series_opts(label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
    visualmap_opts=opts.VisualMapOpts(),
    title_opts=opts.TitleOpts(title="Geo-基本示例")).render("./省份分布.html"))

#-----------------------------------------
#世界地图

from pyecharts.globals import ChartType, SymbolType

geo = Geo()
geo.add_schema(maptype="world")

# 可以在网上查找城市的经纬度
geo.add_coordinate(name="洛杉矶", longitude=-118.15, latitude=34.04)
geo.add_coordinate(name="巴塞罗那", longitude=2.17, latitude=41.38)
geo.add_coordinate(name="孟买", longitude=72.87, latitude=19.07)
geo.add_coordinate(name="墨尔本", longitude=144.96, latitude=-37.81)
geo.add_coordinate(name="圣彼得堡", longitude=30.36, latitude=59.93)
geo.add_coordinate(name="斯图加特", longitude=9.18, latitude=48.77)
geo.add_coordinate(name="圣地亚哥", longitude=-117.16, latitude=32.71)
geo.add_coordinate(name="里约热内卢", longitude=-43.17, latitude=-22.90)
geo.add_coordinate(name="伊尔库斯克", longitude=104.28, latitude=52.28)
geo.add_coordinate(name="曼谷", longitude=100.50, latitude=13.75)
geo.add_coordinate(name="开普敦", longitude=18.42, latitude=-33.92)
geo.add_coordinate(name="阿布扎比", longitude=54.37, latitude=24.45)
geo.add_coordinate(name="檀香山", longitude=-157.85, latitude=21.30)
geo.add_coordinate(name="安克雷奇", longitude=-149.90, latitude=61.21)
geo.add_coordinate(name="东京", longitude=139.76, latitude=35.68)
geo.add_coordinate(name="北京", longitude=116.40, latitude=39.90)
Пример #19
0
cities_coor = [("华盛顿", -77.0, 38.5), ("北京", 116.3, 39.5),
               ("伦敦", 0, 52.0), ("香港", 114.2, 22.3),
               ("巴西利亚", -47.5, -15.4), ("堪培拉", 149.0, -35.1)]
cities_value = [(x[0], int(x[2])) for x in cities_coor]
cities_arrow = []
for city in cities_coor:
    if city[0] != "香港":
        cities_arrow.append((city[0], "香港"))

geo = Geo()

geo.add_schema(maptype="world")

for city in cities_coor:
    geo.add_coordinate(city[0], city[1], city[2])

geo.add(
    "city",
    cities_value,
    type_=ChartType.EFFECT_SCATTER,
    color="green",
    label_opts=opts.LabelOpts(
        is_show=True,
        font_family="Microsoft YaHei",
        position="left",
        formatter="{b}"))
geo.add(
    "impact",
    cities_arrow,
    type_=ChartType.LINES,
Пример #20
0
from pyecharts.render import make_snapshot  # 快照
from snapshot_selenium import snapshot
from pyecharts.globals import ChartType, SymbolType  # 全局配置

data = pd.read_excel("D:\数有引力\魔都商圈\办公项目.xlsx")  # 读取数据
geo_sight_coord = {
    data['项目名称'][i].strip(): [data['经度'][i], data['纬度'][i]]
    for i in range(len(data))
}  # 构造位置字典数据
data_pair = [(data['项目名称'][i].strip(), data['日租金'][i])
             for i in range(len(data))]  # 构造项目租金数据

g = Geo()  # 地理初始化
g.add_schema(maptype="上海")  # 限定上海市范围
for key, value in geo_sight_coord.items():  # 对地理点循环
    g.add_coordinate(key, value[0], value[1])  # 追加点位置

g.add("", data_pair, symbol_size=2)  # 追加项目名称和租金
g.set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                  type='scatter')  # 星散点图scatter

pieces = [
    {
        'max': 3,
        'label': '<3',
        'color': '#00B2EE'
    },
    {
        'min': 3,
        'max': 6,
        '3~6': 'love',
Пример #21
0
long_list = sheet.col_values(21)#经度数据
city1 = sheet.col_values(2)#起飞城市
city2 = sheet.col_values(8)#降落城市
speed = sheet.col_values(22)#飞机速度
vspeed = sheet.col_values(23)#垂直速度
height = sheet.col_values(24)#飞行高度
uptime = sheet.col_values(26)#时间


c = Geo()
# 加载图表模型中的中国地图
c.add_schema(maptype="china")

i = 1
for i in range(1,10):
    c.add_coordinate("航班号" + flightnumber_list[i], long_list[i], lat_list[i])
    # 为自定义的点添加属性
    c.add("geo", [("航班号" + flightnumber_list[i], "航空公司:"+aircname[i]+"  "+city1[i]+"飞往"+city2[i]+"  飞行速度:"+str(speed[i])+"  垂直速度:"+str(vspeed[i])+"  高度:"+str(height[i])+"  时间"+uptime[i])])
    # 设置坐标属性

c.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
# 设置全局属性
c.set_global_opts(
    visualmap_opts=opts.VisualMapOpts(),
    title_opts=opts.TitleOpts(title="航班信息可视化"),
)


# 在 html(浏览器) 中渲染图表
c.render()
# 在 Jupyter Notebook 中渲染图表
Пример #22
0
    y = x[0] + '仓'
    rdc_name.append(y)
    rdc_value.append(1)

#初始化地图
c = Geo(init_opts=opts.InitOpts(width='1500px', height='700px'))
c.add_schema(maptype="china",
             itemstyle_opts=opts.ItemStyleOpts(color="#F0CA00",
                                               border_color="#111"))

#所有城市、RDC仓的坐标加进地图中
City = list(City_cords.keys())
JW = list(City_cords.values())
RDC_JW = list(RDC_cords.values())
for i in range(0, len(City)):
    c.add_coordinate(City[i], JW[i][0], JW[i][1])
for i in range(0, len(RDC_city)):
    c.add_coordinate(rdc_name[i], RDC_JW[i][0], RDC_JW[i][1])

#地图中加RDC仓的点
c.add(
    "RDC仓",
    [list(z) for z in zip(rdc_name, rdc_value)],
    type_="scatter",
    label_opts=opts.LabelOpts(formatter="{b}",
                              color='red',
                              font_size=16,
                              font_weight='bold'),
    color='#3481B8',
    symbol='pin',
    # 标记图形形状,circle,pin,rect,diamon,roundRect,arrow,triangle
Пример #23
0
result = g.render(r'E:\test_opencv\轨迹分析\1.html')
'''

#热力图
import pandas as pd
from pyecharts.charts import Geo
from pyecharts.globals import GeoType
from pyecharts import options as opts

df = pd.read_csv(
    r'E:\test_opencv\轨迹分析\abnormal_device_csv\17201100972_202005.csv',
    encoding='utf-8')
X = df.drop_duplicates(subset=['longitude', 'latitude'])
g = Geo()
g.add_schema(maptype="china")
# 给所有点附上标签 'upload_time'
for index, row in X.iterrows():
    g.add_coordinate(row['upload_time'], row['longitude'], row['latitude'])
upload_time = X.upload_time.values.tolist()
# 给每个点的值赋为 1
data_list = [[item, 1] for item in upload_time]
# 画图
g.add('', data_list, type_=GeoType.HEATMAP, symbol_size=2)
g.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
g.set_global_opts(visualmap_opts=opts.VisualMapOpts(),
                  title_opts=opts.TitleOpts(title="Geo-HeatMap",
                                            pos_left='50%',
                                            pos_top='20'))
# 保存结果到 html
result = g.render(r'E:\test_opencv\轨迹分析\1.html')