2020년 4월 28일 화요일

[Python] Folium 사용

import folium
from folium import Choropleth, Circle, Marker
from folium.plugins import HeatMap, MarkerCluster

# Create a map

m_1 = folium.Map(location=[42.32,-71.0589], tiles='openstreetmap', zoom_start=10) # Display the map m_1

* tiles
cartodbdark_matter
cartodbpositron
cartodbpositronnolabels
cartodbpositrononlylabels
cloudmade
mapbox
mapboxbright
mapboxcontrolroom
openstreetmap
stamenterrain
stamentoner
stamentonerbackground
stamentonerlabels
stamenwatercolor

# Add points to the map

for idx, row in daytime_robberies.iterrows(): Marker([row['Lat'], row['Long']]).add_to(m_2)

# Add Cluster to the map

mc = MarkerCluster() for idx, row in daytime_robberies.iterrows(): if not math.isnan(row['Long']) and not math.isnan(row['Lat']): mc.add_child(Marker([row['Lat'], row['Long']])) m_3.add_child(mc)
def color_producer(val):
    if val <= 12:
        return 'forestgreen'
    else:
        return 'darkred'

# Add a bubble map to the base map

for i in range(0,len(daytime_robberies)): Circle( location=[daytime_robberies.iloc[i]['Lat'], daytime_robberies.iloc[i]['Long']], radius=20,
        popup= '...' ,
        color=color_producer(daytime_robberies.iloc[i]['HOUR'])).add_to(m_4)

# Add a heatmap to the base map

HeatMap(data=crimes[['Lat', 'Long']], radius=10).add_to(m_5)

# Add a choropleth map to the base map

Choropleth(geo_data=districts.__geo_interface__, data=plot_dict, key_on="feature.id", fill_color='YlGnBu', legend_name='Major criminal incidents (Jan-Aug 2018)' ).add_to(m_6)

  • geo_data is a GeoJSON FeatureCollection containing the boundaries of each geographical area.
    • In the code above, we convert the districts GeoDataFrame to a GeoJSON FeatureCollection with the __geo_interface__ attribute.
  • data is a Pandas Series containing the values that will be used to color-code each geographical area.
  • key_on will always be set to feature.id.
    • This refers to the fact that the GeoDataFrame used for geo_data and the Pandas Series provided in data have the same index. To understand the details, we'd have to look more closely at the structure of a GeoJSON Feature Collection (where the value corresponding to the "features" key is a list, wherein each entry is a dictionary containing an "id" key).
  • fill_color sets the color scale.
  • legend_name labels the legend in the top right corner of the map.

2020년 4월 27일 월요일

[라이딩] 190419.자전거 기변





드디어 로드로 기변했다.

CX를 가지고 있으면서도 로드만 타고 ...
타이어를 바꾸고 휠을 바꾸어 로드 형태를 취하고 타고 있었지만
정말 로드만 타고 있어서 로드로 기변해야 하는 것이 아닌가 생각하던 중

주변에 지인이 기변을 하였고, 그 덕에 중고장터를 기웃거리다가
써벨로 프로모션 소식을 접하고 확인해보니
2016년 중고와 거의 비슷한 가격으로 판매하는 것으로 확인하고
이 기회에 로드로 기변할 것을 마음을 굳혔다.

그것도 예전부터 생각해오던 써벨로 R3를... ㅎㅎㅎ
이거 저거 찾아보다 보니 2018년부터 형태가 바뀌어 당분간은 마이너 체인지밖에 없어 2018년식을 타는 경우 늘 신차느낌을 가지고 탈 수 있다고 한다.
(데칼이 바뀌면 그래도 다르게 보이겠지만 ...)

그동안 정들었던 CAADX는 떠나보내주어야 할 것 같다.
CX를 타는 사람들이 많지 않아 쉽게 떠나 보낼 수 있을지는 모르겠다.

[Python] GeoPandas


import geopandas as gpd
(conda install -c conda-forge geopandas -n envname)


< read, dataframe >

1. gdf = gpd.read_file(filesite)
2. df = pd.read_csv(filesite)
   gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.long, df.lat), crs={'init':'epsg:4326'})

* the equal-area projections : Lambert Cylindrical Eaul Area, Africa Albers Equal Are conic
* the equidistant projections : Azimuthal Equidstant projection


< draw >

ax = gdf.plot(figsize=(10, 10), color='whitesmoke', linestyle=':', edgecolor='black', zorder=1)
a.plot(color='maroon', markersize=10, zorder=2, ax=ax)


< re-projecting >

gdf.to_crs(epsg=32630)
regions.to_crs("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")


< attribute >

* POINT
gdf.geometry.x
gdf.geometry.y 
* POLYGON
gdf.geometry.area
* Calculate the total area (in square kilometers)
totalArea = south_america.geometry.to_crs(epsg=3035).area.sum() / 10**6


< Geo Coding >

from geopandas.tools import geocode

result = geocode("The Great Pyramid of Giza", provider="nominatim")

def my_geocoder(row):
    try:
        point = geocode(row, provider='nominatim').geometry.iloc[0]
        return pd.Series({'Latitude': point.y, 'Longitude': point.x, 'geometry': point})
    except:
        return None

universities[['Latitude', 'Longitude', 'geometry']] = universities.apply(lambda x: my_geocoder(x['Name']), axis=1)

print("{}% of addresses were geocoded!".format(
    (1 - sum(np.isnan(universities["Latitude"])) / len(universities)) * 100))

# Drop universities that were not successfully geocoded
universities = universities.loc[~np.isnan(universities["Latitude"])]
universities = gpd.GeoDataFrame(universities, geometry=universities.geometry)
universities.crs = {'init': 'epsg:4326'}
universities.head()

< Spartial Join >

# Use spatial join to match universities to countries in Europe
european_universities = gpd.sjoin(universities, europe)

# Investigate the result
print("We located {} universities.".format(len(universities)))
print("Only {} of the universities were located in Europe (in {} different countries).".format(
    len(european_universities), len(european_universities.name.unique())))
< Porximaty Analysis >
# Measure distance from release to each station
distances = stations.geometry.distance(recent_release.geometry)
distances

two_mile_buffer = stations.geometry.buffer(2*5280)
 # Plot each polygon on the map
folium.GeoJson(two_mile_buffer.to_crs(epsg=4326)).add_to(m)

# Turn group of polygons into single multipolygon
my_union = two_mile_buffer.geometry.unary_union
print('Type:', type(my_union))

# Show the MultiPolygon object
my_union

# The closest station is less than two miles away
my_union.contains(releases.iloc[360].geometry)

# The closest station is more than two miles away
my_union.contains(releases.iloc[358].geometry

200926.가오리코스 라이딩

9/26 골절인지 아닌지 확인 안됨. 이후 미세골절여부 확인 핸드폰을 드는 것도 어려움 9/29 x ray 다시 찍지 않고 이후 재 방문 요청 ...