def get_pipe_total_add_map_by_gu(gu_list, year, tot_num,  start_date, end_date) :  
  df_pipe_total_add_gu_fin = get_pipe_total_add_stat_gus(gu_list, start_date, end_date, tot_num)
  df_pipe_total_add_gu_fin = df_output.transpose()
  df_pipe_total_add_gu_fin = df_pipe_total_add_gu_fin.rename(columns=df_pipe_total_add_gu_fin.iloc[0])
  df_pipe_total_add_gu_fin = df_pipe_total_add_gu_fin.drop(df_pipe_total_add_gu_fin.index[0])
  
  geo_data = "seoul_gu.json"
  with open(geo_data) as f:
      data = json.loads(f.read())
  
  data_list = []
  for i in range(len(data['features'])) : 
    data['features'][i]['properties']['자치구명'] = data['features'][i]['properties'].pop("name")
    for j in range(len(df_pipe_total_add_gu_fin)) : 
      if data['features'][i]['properties']["자치구명"] == df_pipe_total_add_gu_fin.index[j] : 
        del data['features'][i]['properties']['code']
        del data['features'][i]['properties']['base_year']
        del data['features'][i]['properties']['name_eng']
        data['features'][i]['properties']["비율"] = round(df_pipe_total_add_gu_fin[year][j], 5)
        data['features'][i]['properties']["분석기간"] =  str(year) + "년"
        data_list.append(data['features'][i])

  data['features'] = data_list  
  token = 'pk.eyJ1IjoiZHVjazk2NjciLCJhIjoiY2thNzRiMXhxMGQ5NTJ0cXB0dGpmZ3RrOSJ9.f45On_lrv6Nm4iO7oCg7nw'
  res, bins = pd.qcut(df_pipe_total_add_gu_fin[year], 3, retbins=True)
  color_breaks = color_breaks = list(bins) 
  color_stops = create_color_stops(color_breaks, colors='BuPu')

  viz = ChoroplethViz(access_token=token, data=data, color_property= "비율", color_stops=color_stops, center = [126.986, 37.565] , zoom=9.5, line_width=2)
  viz.create_html('templates/map_{}.html'.format(tot_num))
  return print('생성')   
Beispiel #2
0
def plot_img_csv(folder, csv='log.csv', delim=" ", dispCol="Z"):
    
    """
    Plot image GPS csv on a map with mapbox
    
    Parameters
    ----------
    folder: string
           working directory
        
    csv: string
         csv name - log.csv is default
    
    delim: string
          delimiter of csv " " (space) is defaut;

    """
    
    df = pd.read_csv(csv, sep=" ", index_col=False)
    
    token = 'pk.eyJ1IjoibWljYXNlbnNlIiwiYSI6ImNqYWx5dWNteTJ3cWYzMnBicmZid3g2YzcifQ.Zrq9t7GYocBtBzYyT3P4sw'
    color_stops = create_color_stops(np.linspace( df[dispCol].min(), 
                                                 df[dispCol].max(),
                                                 num=8), colors='YlOrRd')
    data = df_to_geojson(df, ["#F=N", "Z"],lat='Y',lon='X')
    viz = CircleViz(data, access_token=token, color_property=dispCol,
                    color_stops=color_stops,
                    center=[df['X'].median(),df['Y'].median()], 
                    zoom=16, height='600px',
                    style='mapbox://styles/mapbox/satellite-streets-v9')
    viz.show()
def get_map_by_gu(gu_list, start_date, end_date, tot_num):
    df_fin = df[(df['datetime'] >= start_date)
                & (df['datetime'] <= dt.datetime.strptime(end_date, '%Y-%m') +
                   relativedelta(months=1))]
    df_output = pd.DataFrame(df_fin.groupby(
        df_fin['유형_소']).count()).reset_index()[['유형_소', '번호']]

    df_output.columns = ['구', '민원수']
    YM = end_date.split('-')[0] + '년'

    df_pop_gu = df_pop[df_pop['동'] == '소계'][['구', YM]].reset_index(drop=True)
    df_pop_gu_fin = pd.merge(df_output, df_pop_gu, on='구', how='left')
    df_pop_gu_fin['1000명당 민원수'] = (df_pop_gu_fin['민원수'] /
                                   df_pop_gu_fin[YM]) * 1000

    if '서울시' in gu_list:
        gu_list = list(df_dong_list.columns[1:])
    df_pop_gu_fin = df_pop_gu_fin[df_pop_gu_fin['구'].str.contains(
        '|'.join(gu_list))].reset_index(drop=True)

    geo_data = "seoul_gu.json"
    with open(geo_data) as f:
        data = json.loads(f.read())

    data_list = []
    for i in range(len(data['features'])):
        data['features'][i]['properties']['자치구명'] = data['features'][i][
            'properties'].pop("name")
        for j in range(len(df_pop_gu_fin)):
            if data['features'][i]['properties']["자치구명"] == df_pop_gu_fin["구"][
                    j]:
                del data['features'][i]['properties']['code']
                del data['features'][i]['properties']['base_year']
                del data['features'][i]['properties']['name_eng']
                data['features'][i]['properties']["1000명당 민원수"] = round(
                    df_pop_gu_fin["1000명당 민원수"][j], 5)
                data['features'][i]['properties']["민원수(건)"] = int(
                    df_output["민원수"][j])
                data_list.append(data['features'][i])

    data['features'] = data_list
    token = 'pk.eyJ1IjoiZHVjazk2NjciLCJhIjoiY2thNzRiMXhxMGQ5NTJ0cXB0dGpmZ3RrOSJ9.f45On_lrv6Nm4iO7oCg7nw'
    res, bins = pd.qcut(df_pop_gu_fin['1000명당 민원수'], 3, retbins=True)
    color_breaks = color_breaks = list(bins)
    color_stops = create_color_stops(color_breaks, colors='BuPu')

    viz = ChoroplethViz(access_token=token,
                        data=data,
                        color_property='1000명당 민원수',
                        color_stops=color_stops,
                        center=[126.986, 37.565],
                        zoom=9.5,
                        line_width=2)
    viz.create_html('templates/map_{}.html'.format(tot_num))
    return print('생성')
def get_area_map_by_dong(gu, dong_list, start_date, end_date, tot_num) : 
  df_fin = df[(df['datetime'] >= start_date)&(df['datetime'] <= dt.datetime.strptime(end_date, '%Y-%m') + relativedelta(months=1))][df['유형_소'] == gu]
  df_output = pd.DataFrame(df_fin.groupby(df_fin['동_수정']).count()).reset_index()[['동_수정','번호']]

  df_output.columns = ['동', '민원수']
  YM = int(end_date.split('-')[0])

  df_area_dong = df_area[df_area['구'] == gu][['동',YM]].reset_index(drop=True)
  df_area_dong_fin = pd.merge(df_output, df_area_dong, on = '동', how='left' )
  df_area_dong_fin['면적당 민원수'] = df_area_dong_fin['민원수']/df_area_dong_fin[YM]

  geo_data = "seoul_dong_v0.2.json"
  with open(geo_data,encoding="CP949") as f:
      data = json.loads(f.read())

  if dong_list == ['전체'] :
    dong_list = list(df_dong_list[gu].dropna())
    df_area_dong_fin = df_area_dong_fin[df_area_dong_fin['동'].str.contains('|'.join(dong_list))].reset_index(drop=True)

  else :
    df_area_dong_fin = df_area_dong_fin[df_area_dong_fin['동'].str.contains('|'.join(dong_list))].reset_index(drop=True)

  data_list = []
  for i in range(len(data['features'])) : 
    data['features'][i]['properties']['자치구명'] = data['features'][i]['properties'].pop("sggnm")
    data['features'][i]['properties']['동명'] = data['features'][i]['properties'].pop("동")
    for j in range(len(df_area_dong_fin)) : 
      if data['features'][i]['properties']['자치구명'] == gu and data['features'][i]['properties']["동명"] == df_area_dong_fin["동"][j] : 
            del data['features'][i]['properties']['OBJECTID']
            del data['features'][i]['properties']['adm_cd']
            del data['features'][i]['properties']['adm_cd2']
            del data['features'][i]['properties']['adm_nm']
            del data['features'][i]['properties']['sgg']
            del data['features'][i]['properties']['sido']
            del data['features'][i]['properties']['sidonm']

            data['features'][i]['properties']["면적당 민원수"] = round(df_area_dong_fin["면적당 민원수"][j], 5)
            data['features'][i]['properties']["분석기간"] =  start_date + "~" + end_date
            data_list.append(data['features'][i])

  data['features'] = data_list
  token = 'pk.eyJ1IjoiZHVjazk2NjciLCJhIjoiY2thNzRiMXhxMGQ5NTJ0cXB0dGpmZ3RrOSJ9.f45On_lrv6Nm4iO7oCg7nw'
  res, bins = pd.qcut(df_area_dong_fin['면적당 민원수'], 3, retbins=True)
  color_breaks = list(bins) 
  color_stops = create_color_stops(color_breaks, colors='BuPu')
  
  viz = ChoroplethViz(access_token=token, data=data, color_property='면적당 민원수', color_stops=color_stops, center=[126.986, 37.565], zoom=9.5, line_width=2)
  viz.create_html('templates/map_{}.html'.format(tot_num))
  return print('생성')
Beispiel #5
0
def test_display_vector_extruded_ChoroplethViz(display):
    """Assert that show calls the mocked display function when using data-join technique
    for ChoroplethViz.
    """
    data = [{
        "id": "06",
        "name": "California",
        "density": 241.7
    }, {
        "id": "11",
        "name": "District of Columbia",
        "density": 10065
    }, {
        "id": "25",
        "name": "Massachusetts",
        "density": 840.2
    }, {
        "id": "30",
        "name": "Montana",
        "density": 6.858
    }, {
        "id": "36",
        "name": "New York",
        "density": 412.3
    }, {
        "id": "49",
        "name": "Utah",
        "density": 34.3
    }, {
        "id": "72",
        "name": "Puerto Rico",
        "density": 1082
    }]

    viz = ChoroplethViz(data,
                        vector_url='mapbox://mapbox.us_census_states_2015',
                        vector_layer_name='states',
                        vector_join_property='STATEFP',
                        data_join_property='id',
                        color_property='density',
                        color_stops=create_color_stops([0, 50, 100, 500, 1500],
                                                       colors='YlOrRd'),
                        height_property='density',
                        height_stops=create_numeric_stops(
                            [0, 50, 100, 500, 1500, 10000], 0, 1000000),
                        access_token=TOKEN)
    viz.show()
    display.assert_called_once()
def get_map_compare_gu(start_date, end_date, tot_num):
    df_fin = df[(df['datetime'] > start_date)
                & (df['datetime'] <= dt.datetime.strptime(end_date, '%Y-%m') +
                   relativedelta(months=1))]
    df_output = pd.DataFrame(df_fin.groupby(
        df_fin['유형_소']).count()).reset_index()[['유형_소', '번호']]
    df_output.columns = ['구', '민원수(건)']

    start_date = start_date.split("-")[0] + '년 ' + start_date.split(
        "-")[1] + '월'
    end_date = end_date.split("-")[0] + '년 ' + end_date.split("-")[1] + '월'

    geo_data = "seoul_gu.json"
    with open(geo_data) as f:
        data = json.loads(f.read())

    for i in range(len(data['features'])):
        data['features'][i]['properties']['자치구명'] = data['features'][i][
            'properties'].pop("name")
        for j in range(len(df_output)):
            if data['features'][i]['properties']["자치구명"] == df_output["구"][j]:
                del data['features'][i]['properties']['code']
                del data['features'][i]['properties']['base_year']
                del data['features'][i]['properties']['name_eng']
                data['features'][i]['properties'][
                    "분석기간"] = start_date + "~" + end_date
                data['features'][i]['properties']["민원수(건)"] = int(
                    df_output["민원수(건)"][j])

    token = 'pk.eyJ1IjoiZHVjazk2NjciLCJhIjoiY2thNzRiMXhxMGQ5NTJ0cXB0dGpmZ3RrOSJ9.f45On_lrv6Nm4iO7oCg7nw'
    res, bins = pd.qcut(df_output['민원수(건)'], 3, retbins=True)
    color_breaks = list(bins)
    color_stops = create_color_stops(color_breaks, colors='BuPu')

    viz = ChoroplethViz(access_token=token,
                        data=data,
                        color_property='민원수(건)',
                        color_stops=color_stops,
                        center=[126.986, 37.565],
                        zoom=9.5,
                        line_width=2)
    viz.create_html('templates/map_{}.html'.format(tot_num))
    return print("생성")
Beispiel #7
0
def test_display_vector_LinestringViz(display):
    """Assert that show calls the mocked display function when using data-join technique
    for LinestringViz.
    """
    data = [{
        "elevation": x,
        "weight": random.randint(0, 100)
    } for x in range(0, 21000, 10)]

    viz = LinestringViz(data,
                        vector_url='mapbox://mapbox.mapbox-terrain-v2',
                        vector_layer_name='contour',
                        vector_join_property='ele',
                        data_join_property='elevation',
                        color_property="elevation",
                        color_stops=create_color_stops([0, 50, 100, 500, 1500],
                                                       colors='YlOrRd'),
                        line_width_property='weight',
                        line_width_stops=create_numeric_stops(
                            [0, 25, 50, 75, 100], 1, 6),
                        access_token=TOKEN)
    viz.show()
    display.assert_called_once()
Beispiel #8
0
def test_color_stops_custom_null():
    """Create invalid number of color stops that do not match the number of breaks"""
    with pytest.raises(ValueError):
        create_color_stops([0, 1, 2],
                           colors=['red', 'yellow', 'green', 'grey'])
Beispiel #9
0
def test_color_stops_custom_invalid():
    """Create invalid color stops from custom color breaks and throw value error"""
    with pytest.raises(ValueError):
        create_color_stops([0, 1, 2], colors=['x', 'yellow', 'green'])
Beispiel #10
0
def test_color_stops_custom():
    """Create color stops from custom color breaks"""
    stops = create_color_stops([0, 1, 2], colors=['red', 'yellow', 'green'])
    assert stops == [[0, "red"], [1, "yellow"], [2, "green"]]
Beispiel #11
0
def test_color_stops():
    """Create color stops from breaks using colorBrewer"""
    stops = create_color_stops([0, 1, 2], colors='YlGn')
    assert stops == [[0, "rgb(247,252,185)"], [1, "rgb(173,221,142)"],
                     [2, "rgb(49,163,84)"]]
Beispiel #12
0
# ## Mapping capture locations using MapboxGL
# 
# Below we use the `mapboxgl` extension to plot the measured DLS yaw (or heading) angle from each image's meatadata over the whole imageset. We draw circles at each image location, and then color the circle based on the yaw value. 

# In[ ]:


import math
import numpy as np
from mapboxgl.viz import *
from mapboxgl.utils import df_to_geojson, create_radius_stops, scale_between
from mapboxgl.utils import create_color_stops

#Insert your mapbox token here
token = 'pk.eyJ1IjoibWljYXNlbnNlIiwiYSI6ImNqYWx5dWNteTJ3cWYzMnBicmZid3g2YzcifQ.Zrq9t7GYocBtBzYyT3P4sw'
color_stops = create_color_stops(np.linspace(-math.pi,math.pi,num=8),colors='YlOrRd')
data = df_to_geojson(df,columns[3:],lat='latitude',lon='longitude')
viz = CircleViz(data, access_token=token, color_property='dls-yaw',
                color_stops=color_stops,
                center=[df['longitude'].median(),df['latitude'].median()], 
                zoom=16, height='600px',
                style='mapbox://styles/mapbox/satellite-streets-v9')
viz.show()


# ## Plotting capture metadata

# In[ ]:


import matplotlib.pyplot as plt
Beispiel #13
0
from mapboxgl.viz import *
from mapboxgl.utils import *
from mapboxgl.utils import create_color_stops

# 환경변수에서 자신의 mapbox token 을 가져옵니다.
#token = os.getenv('MAPBOX_ACCESS_TOKEN')

token = 'pk.eyJ1IjoianVueWVvbmdhaG4wMzE5IiwiYSI6ImNrajY0MHI2djBoOTQzM3FnaGk2dTA0emsifQ.spSQ5Bz-EdJeUlFy-IEHFQ'

# 서울시 중심부의 경도, 위도 입니다. 
center = [126.986, 37.565]

# 시각화 할 값에 따른 색상의 범주를 지정해줍니다.

color_breaks = [0, 10000, 20000, 30000, 40000, 50000]
color_stops = create_color_stops(color_breaks, colors='BuPu')

# color_stops 에는 다음과 같은 값이 들어갑니다.
# color_stops = [
#     [0, 'rgb(237,248,251)'],
#     [10000, 'rgb(191,211,230)'],
#     [20000, 'rgb(158,188,218)'],
#     [30000, 'rgb(140,150,198)'],
#     [40000, 'rgb(136,86,167)'],
#     [50000, 'rgb(129,15,124)']
# ]

# ChoroplethViz 를 그립니다.
viz = ChoroplethViz(
    access_token=token,
    data=state_geo,
def get_map_compare_dong(gu, start_date, end_date, tot_num):
    df_fin = df[(df['datetime'] >= start_date)
                & (df['datetime'] <= dt.datetime.strptime(end_date, '%Y-%m') +
                   relativedelta(months=1))][df['유형_소'] == gu]
    df_output = pd.DataFrame(df_fin.groupby(
        df_fin['동_수정']).count()).reset_index()[['동_수정', '번호']]
    df_output.columns = ['동', '민원수(건)']

    start_date = start_date.split("-")[0] + '년 ' + start_date.split(
        "-")[1] + '월'
    end_date = end_date.split("-")[0] + '년 ' + end_date.split("-")[1] + '월'

    geo_data = "seoul_dong_v0.2.json"
    with open(geo_data) as f:
        data = json.loads(f.read())

    data_list = []
    for i in range(len(data['features'])):
        data['features'][i]['properties']['자치구명'] = data['features'][i][
            'properties'].pop("sggnm")
        data['features'][i]['properties']['동명'] = data['features'][i][
            'properties'].pop("동")

        for j in range(len(df_output)):
            if data['features'][i]['properties']['자치구명'] == gu and data[
                    'features'][i]['properties']["동명"] == df_output["동"][j]:
                data['features'][i]['properties']["민원수(건)"] = int(
                    df_output["민원수(건)"][j])
                del data['features'][i]['properties']['OBJECTID']
                del data['features'][i]['properties']['adm_cd']
                del data['features'][i]['properties']['adm_cd2']
                del data['features'][i]['properties']['adm_nm']
                del data['features'][i]['properties']['sgg']
                # del data['features'][i]['properties']['sggnm']
                del data['features'][i]['properties']['sido']
                del data['features'][i]['properties']['sidonm']
                data['features'][i]['properties'][
                    "분석기간"] = start_date + "~" + end_date
                data['features'][i]['properties']["민원수(건)"] = int(
                    df_output["민원수(건)"][j])
                data_list.append(data['features'][i])

    data['features'] = data_list
    token = 'pk.eyJ1IjoiZHVjazk2NjciLCJhIjoiY2thNzRiMXhxMGQ5NTJ0cXB0dGpmZ3RrOSJ9.f45On_lrv6Nm4iO7oCg7nw'
    res, bins = pd.qcut(df_output['민원수(건)'], 3, retbins=True)
    color_breaks = list(bins)
    color_stops = create_color_stops(color_breaks, colors='BuPu')

    viz = ChoroplethViz(
        access_token=token,
        data=data,
        color_property='민원수(건)',
        color_stops=color_stops,
        center=[
            data['features'][0]["geometry"]["coordinates"][0][0][0][0],
            data['features'][0]["geometry"]["coordinates"][0][0][0][1]
        ],
        zoom=9.5,
        line_width=2)
    viz.create_html('templates/map_{}.html'.format(tot_num))
    return print('생성')
Beispiel #15
0
def test_bad_ramp():
    with pytest.raises(ValueError):
        create_color_stops([1, 2, 3], colors='DoubleRainbow')
Beispiel #16
0
def test_colors():
    assert create_color_stops([1, 2, 3], colors='PuOr') == \
        [[1, 'rgb(241,163,64)'], [2, 'rgb(247,247,247)'], [3, 'rgb(153,142,195)']]
Beispiel #17
0
def test_too_many_colors():
    with pytest.raises(ValueError):
        create_color_stops(list(range(100)), colors='PuOr')