Боке патчи не загружают мультиполигоны с CDS - PullRequest
0 голосов
/ 13 февраля 2020

Я хотел бы использовать CDS (ColumnDataSource), поскольку я буду обновлять карту с помощью ползунка, я ЗНАЮ, что могу использовать GeoJsonDataSource, а также что можно будет обновить ее с помощью Geo json, хотя я буду встраивать ее к веб-приложению, и geo json будет чрезвычайно тяжелым, несмотря на то, что я предпочитаю работать с CDS, потому что у меня больше контроля над всем этим. Также есть ли другой способ получить столбец 'geometry' без его растворения (много памяти)? Поэтому, когда это мультиполигон, патчи не будут загружать его, что даст мне только простые полигоны. Если кто-то может мне помочь. Заранее спасибо! Данные доступны здесь прокрутите вниз и выберите Локальные избирательные участки 2008 года

import pandas as pd
import numpy as np
import geopandas as gpd
from bokeh.io import (output_notebook, show, curdoc, output_file)
from bokeh.plotting import figure
from bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar, ColumnDataSource
from bokeh.models.glyphs import MultiPolygons
from copy import deepcopy
from bokeh.palettes import Pastel2, viridis, inferno, magma, Paired, Spectral, brewer, Greens, YlGn
import matplotlib.pyplot as plt
output_notebook()

geoIrl = gpd.read_file('Census2011_Local_Electoral_Areas_2008.shp')
irlg = geoIrl[['COUNTY','geometry']]
irl = irlg.dissolve(by='COUNTY', aggfunc='sum')
dfirl = deepcopy(irl)


#extracting the xs and ys
def getPolyCoords(row, geom, coord_type):
    """Returns the coordinates ('x|y') of edges/vertices of a Polygon/others"""

    # Parse the geometries and grab the coordinate
    geometry = row[geom]
    #print(geometry.type)

    if geometry.type=='Polygon':
        if coord_type == 'x':
            # Get the x coordinates of the exterior
            # Interior is more complex: xxx.interiors[0].coords.xy[0]
            return list( geometry.exterior.coords.xy[0] )
        elif coord_type == 'y':
            # Get the y coordinates of the exterior
            return list( geometry.exterior.coords.xy[1] )

    if geometry.type in ['Point', 'LineString']:
        if coord_type == 'x':
            return list( geometry.xy[0] )
        elif coord_type == 'y':
            return list( geometry.xy[1] )

    if geometry.type=='MultiLineString':
        all_xy = []
        for ea in geometry:
            if coord_type == 'x':
                all_xy.append(list( ea.xy[0] ))
            elif coord_type == 'y':
                all_xy.append(list( ea.xy[1] ))
        return all_xy

    if geometry.type=='MultiPolygon':
        all_xy = []
        for ea in geometry:
            if coord_type == 'x':
                all_xy.append(list( ea.exterior.coords.xy[0] ))
            elif coord_type == 'y':
                all_xy.append(list( ea.exterior.coords.xy[1] ))
        return all_xy

    else:
        # Finally, return empty list for unknown geometries
        return []

dfirl['xs'] = dfirl.apply(getPolyCoords, geom='geometry', coord_type='x', axis=1)
dfirl['ys'] = dfirl.apply(getPolyCoords, geom='geometry', coord_type='y', axis=1)

rX = 'CARLOW', 'CAVAN', 'CLARE', 'CORK', 'DONEGAL', 'DUBLIN', 'GALWAY','KERRY', 'KILDARE', 'KILKENNY', 'LAOIS', 'LEITRIM', 'LIMERICK','LONGFORD', 'LOUTH', 'MAYO', 'MEATH', 'MONAGHAN', 'OFFALY', 'ROSCOMMON', 'SLIGO', 'TIPPERARY', 'WATERFORD', 'WESTMEATH', 'WEXFORD', 'WICKLOW'
srcmap = ColumnDataSource(data=dict(x=rX, y02=df_map['2002'], y06=df_map['2006'], y11=df_map['2011'], y16=df_map['2016'], xs=df_map['xs'], ys=df_map['ys']))

pc = figure(title = 'test', tools = '', x_axis_location = None, y_axis_location = None)

pc.patches('xs', 'ys', fill_alpha = 0.7, line_width = 0.5, source = srcmap)
#pc.grid.grid_line_color=None
show(pc)

Если я выберу индивидуальный мультиполигон, я смогу построить его, используя патчи.

xstest =df_map.loc['DUBLIN']['xs']
ystest = df_map.loc['DUBLIN']['ys']
pc = figure(title = 'test', tools = '', x_axis_location = None, y_axis_location = None)
pc.patches(xs=xstest, ys=ystest, fill_alpha = 0.7, line_width = 0.5)
show(pc)

geojson xs_ys_CDS individually

...