def test_simple_linear(): linear = cm.LinearColormap(['green', 'yellow', 'red'], vmin=3., vmax=10., width='30%') linear = cm.LinearColormap(['red', 'orange', 'yellow', 'green'], index=[0, 0.1, 0.9, 1.]) linear._repr_html_()
def add_colormap(data, color_column=None, color_list=None, color_min_val=None, color_max_val=None, step=None, fill_color=None, output_color_ramp=False): """Outputs a color ramp as a list or as a color ramp function used for visualisation when 'output_color_ramp' is True.\n color_column: field to be used to calculate the color ramp.\n color_list: list of colors to build the color ramp ex ['green','white', 'red'] otherwise sets a red to blue ramp as a default.\n color_min_val: set a minimum range for the color ramp. Used when limiting the color range.\n color_max_val: set a maximum range for the color ramp. Used when limiting the color range.\n step: conver to steps instead of a continuas range\n fill_color: Sets a fill color, used mainly in the other functions.\n output_color_ramp: outputs a color ramp dunction instead that can be visualised""" df = data.copy() try: if color_column == None: #set default or fill color if color column isn't provided fill_color = '#49B5FA' if not fill_color else fill_color color_ramp = cm.LinearColormap([fill_color, fill_color]) colors = [color_ramp(0) for x in range(len(df))] elif df[color_column].dtype in [np.int, np.float]: #process linear colormaps color_ramp = cm.LinearColormap( color_list if color_list != None else ['#FE6C94', '#27AAFF'], vmin=color_min_val if color_min_val != None else df[color_column].min(), vmax=color_max_val if color_max_val != None else df[color_column].max()) color_ramp = color_ramp.to_step( step) if step != None else color_ramp colors = [color_ramp(i) for i in df[color_column].to_list()] else: #process categorical colormaps keys = df[color_column].unique() step_map = np.arange(start=0, stop=1, step=1 / len(keys)) color_ramp = cm.LinearColormap( color_list) if color_list else cm.linear.Set1_08 color_ramp = color_ramp.to_step(len(keys) + 1) values = [color_ramp(x) for x in step_map] map_dict = dict(zip(keys, values)) colors = df[color_column].map(map_dict).to_list() except: color_ramp = cm.LinearColormap(['#EE0000', '#EE0000']) colors = [color_ramp(0) for i in range(len(df))] if output_color_ramp: return (color_ramp) else: return (colors)
def choropleth_map(df_aggreg, hex_id_field, geometry_field, value_field, layer_name, initial_map=None, kind="filled_nulls", border_color='#ffffff', fill_opacity=0.4, border_opacity=0.3, with_legend=False): """Plots a Choropleth Map with folium""" if initial_map is None: initial_map = base_empty_map() # the custom colormap depends on the map kind if kind == "linear": min_value = df_aggreg[value_field].min() max_value = df_aggreg[value_field].max() custom_cm = cm.LinearColormap(['green', 'yellow', 'red'], vmin=min_value, vmax=max_value) elif kind == "outlier": # for outliers, values would be -1,0,1 custom_cm = cm.LinearColormap(['blue', 'white', 'red'], vmin=-1, vmax=1) elif kind == "filled_nulls": min_value = df_aggreg[df_aggreg[value_field] > 0][value_field].min() max_value = df_aggreg[df_aggreg[value_field] > 0][value_field].max() # m = round((min_value + max_value) / 2, 0) m = (min_value + max_value) / 2.0 custom_cm = cm.LinearColormap(['silver', 'green', 'yellow', 'red'], index=[0, min_value, m, max_value], vmin=min_value, vmax=max_value) else: custom_cm = None # create geojson data from dataframe geojson_data = hexagons_dataframe_to_geojson(df_aggreg, hex_id_field, geometry_field, value_field) # plot on map GeoJson( geojson_data, style_function=lambda feature: { 'fillColor': custom_cm(feature['properties']['value']), 'color': border_color, 'opacity': border_opacity, 'weight': 0.2, 'fillOpacity': fill_opacity }, name=layer_name ).add_to(initial_map) # add legend (not recommended if multiple layers) if with_legend is True: custom_cm.add_to(initial_map) return initial_map
def BuildColormap(minval, maxval): # Construct a colormap (if value brackets 0, try to set scale to be asymetric around 0) if (minval < 0) & (maxval > 0): cmap = cm.LinearColormap(colors=cmapcolors_sym, index=[minval, 0, maxval], vmin=minval, vmax=maxval) else: cmap = cm.LinearColormap(colors=cmapcolors_linear, vmin=minval, vmax=maxval) return cmap
def color_map_set(): """ Set the different ranges of hourly rates, generate color_maps that span them, and add a caption to the color_map legend. """ colormapcheap = cm.LinearColormap(colors=['purple', 'blue', 'lightblue', 'green'],\ vmin=1, vmax=MAX_CHEAP) colormapmid = cm.LinearColormap(colors=['green', 'lightgreen', 'yellow', 'orange'],\ vmin=MAX_CHEAP, vmax=MAX_MID) colormapexpensive = cm.LinearColormap(colors=['orange', 'salmon', 'red', 'darkred'],\ vmin=MAX_MID, vmax=MAX_EXPENSIVE) colormapcheap.caption = 'The time you save costs you this hourly rate ($/hr)' colormapmid.caption = 'The time you save costs you this hourly rate ($/hr)' colormapexpensive.caption = 'The time you save costs you this hourly rate ($/hr)' return [colormapcheap, colormapmid, colormapexpensive]
def prepare_and_draw_colormap(grouped_by_zone, column = 'PULocationID', file='Colormaps_.html'): """ Arguments: grouped_by_zone -- the data frame merged previously with taxi_zone_lookup column -- the column used in marging (i.e. PULocationID, DOLocationID) file -- name of the file where the map will be saved """ # Finding minimal and maximal value in dataset if column=='difference': min_val = grouped_by_zone[column].min() max_val = grouped_by_zone[column].max() zones_counts = grouped_by_zone[column].reset_index() zone_dict = zones_counts.set_index('Zone')['difference'] # Defining function for intensity od colors linear = cm.LinearColormap( ['blue', 'white', 'red'], vmin=-1*max_val, vmax=max_val) else: min_val = grouped_by_zone[column].min()[0] max_val = grouped_by_zone[column].max()[0] # Creating the dictionary with {'Zone': number of trips} zones_counts = grouped_by_zone[column]['count'].reset_index() zone_dict = zones_counts.set_index('Zone')['count'] # Defining function for intensity od colors linear = cm.LinearColormap( ['green', 'yellow', 'red'], vmin=min_val, vmax=max_val) # Defining the function for coloring def my_color_function(feature, zone_dict = zone_dict, names = False): try: return linear(zone_dict[feature['properties']['zone']]) except Exception as e: print(e) return '#FFFFFF' # Drawing the map m = folium.Map([40.7, -74], tiles='cartodbpositron', zoom_start=10) linear.add_to(m) # adding the colorbar gj = folium.GeoJson( data = geojson, style_function=lambda feature: { 'fillColor': my_color_function(feature), 'color': 'black', 'weight': 2, 'dashArray': '5, 5', 'fillOpacity': 0.5, 'popup': "aaa" } ).add_to(m) m.save(file) return m
def choropleth_map(df_agg, value_col, name, border_color='black', fill_opacity=0.7, initial_map=None, with_legend=False, kind='linear'): min_value = df_agg[value_col].min() max_value = df_agg[value_col].max() m = round((min_value + max_value) / 2, 0) res = h3.h3_get_resolution(df_agg.loc[0, 'hex_id']) if initial_map is None: initial_map = Map( location=[39.970208, -83.000645], zoom_start=13, tiles='cartodbpositron', attr=( '© <a href="http://www.openstreetmap.org/copyright">' + 'OpenStreetMap</a> contributors © <a href="http://cartodb.' + 'com/attributions#basemaps">CartoDB</a>' ) ) if kind == 'linear': custom_cm = cm.LinearColormap( ['green', 'yellow', 'red'], vmin=min_value, vmax=max_value) elif kind == 'outlier': custom_cm = cm.LinearColormap( ['blue', 'white', 'red'], vmin=min_value, vmax=max_value) geojson_data = hexagons_dataframe_to_geojson( df_hex=df_agg, value_col=value_col) GeoJson( geojson_data, style_function=lambda feature: { 'fillColor': custom_cm(feature['properties']['value']), 'color': border_color, 'weight': 1, 'fillOpacity': fill_opacity }, name=name ).add_to(initial_map) if with_legend is True: custom_cm.add_to(initial_map) return initial_map
def createMap(df): # dataframe df_ratio = df['elhunytak'] / df['nepesseg'] maxCasesR = df_ratio.max() maxCases = df['elhunytak'].max() map = fl.Map(location=[47.20, 19.50], tiles='cartodbpositron', zoom_start=8) colormap = cm.LinearColormap( colors=['green', 'lightgreen', 'yellow', 'orange', 'red', 'black'], vmin=0, vmax=maxCasesR * 100) colormap.add_to(map) scale_factor_circle = 10000.0 / maxCases # 5000 - max radius of city (in metre for i in range(df.shape[0]): row = df.iloc[i] fl.Circle( location=[row['lats'], row['longs']], tooltip=str_elhunyt(row), radius=min(max(1000, row['elhunytak'] * scale_factor_circle), 10000), color=colormap(df_ratio.iloc[i] * 100), # radius = max(1, df_ratio.iloc[i]* scale_factor_circle), # color = color, opacity=0.75, fill=True).add_to(map) return map
def createMap(df): # dataframe map = fl.Map(location=[47.20, 19.50], zoom_start=8) colormap = cm.LinearColormap( colors=['yellow', 'green', 'blue', 'purple', 'red'], vmin=0, vmax=100) colormap.add_to(map) base_map = fl.FeatureGroup(name='Alaptérkép', overlay=True, control=False, show=False) fl.TileLayer(tiles='cartodbpositron').add_to(base_map) base_map.add_to(map) layer1 = createLayer(df, 'Covid pozitív gondozott/férőhely', 'cpoz_gondozott_szam', 'ferohely', str_gondozottak) layer1.add_to(map) # layer2 = createLayer(df, 'Elhunyt covid pozitív gondozott/férőhely', 'cpoz_gondozott_elhunyt', 'ferohely', str_gondozottak) layer2.add_to(map) # layer3 = createLayer(df, 'Covid pozitív dolgozó/dolgozó létszám', 'cpoz_dolgozo_szam', 'dolgozo_letszam', str_dolgozok) layer3.add_to(map) # layer4 = createLayer(df, 'Elhunyt covid pozitív dolgozó/dolgozó létszám', 'cpoz_dolgozo_elhunyt', 'dolgozo_letszam', str_dolgozok) layer4.add_to(map) fl.map.LayerControl(collapsed=False).add_to(map) return map
def get_colormap(): '''Add a colorbar for the distance to grocery stores''' colormap = cm.LinearColormap(colors=['g', 'y', 'r'], vmin=minval, vmax=maxval).to_step(ncolor) colormap.caption = 'Distance to nearest grocery store (miles)' return colormap
def interactive_map(jour, poll): occ_day = occitanie_df[occitanie_df['nom_poll'] == poll] linear = cm.LinearColormap(['green', 'yellow', 'red'], vmin=min(occ_day['valeur']), vmax=max(occ_day['valeur'])) occ_day = occ_day[occ_day['date'] == jour] map_conf = folium.Map(location=[43, 2.15], zoom_start=7.4, tiles='Stamen Terrain') for i in range(0, len(occ_day)): folium.Circle( location=[occ_day.iloc[i]['Y'], occ_day.iloc[i]['X']], popup=occ_day.iloc[i]['nom_station'], radius=occ_day.iloc[i]['valeur'] * 300, color='black', fill=True, fill_color=linear(occ_day.iloc[i]['valeur']), fill_opacity=0.5, opacity=0.4, ).add_to(map_conf) return (map_conf)
def showFemale(request): global g global getGu crime_type="" loc_list=[] if request.method=="POST": filter_value=request.POST['female_filter'] crime_type="전체_"+filter_value female_total=Female2.objects.filter(gu=getGu,female2_crime_type=crime_type).all() linear = cmp.LinearColormap( [ 'green','blue','red'], vmin=10, vmax=300) map = folium.Map(location=[37.55582994870823, 126.9726320033982],zoom_start=15) for loc in female_total: gis= Geometry(loc.female2_crime_loc.hex()[8:]) contain_coordinate=shape(gis.geojson) crime_location={"type":"Feature","properties":{'area':math.ceil(round(contain_coordinate.length,5)*100000)},"geometry":gis.geojson} folium.GeoJson(crime_location,style_function=lambda feature: { 'fillColor': linear(feature['properties']['area']), 'color': linear(feature['properties']['area']), 'weight': 1 }).add_to(map) linear.add_to(map) maps=map._repr_html_() return render(request, 'home.html',{'map':maps})
def get_map(activity_id, coords, z=None): """ Get a folium map of the activity given the coords Input should be a list of tuples: (lat, lon) If specified, uses the third variable (e.g. pace) as plot color """ ctr = tuple(np.mean(coords, axis=0)) m = folium.Map(location=ctr, zoom_start=13, tiles='OpenStreetMap') if z is None: kw = dict(opacity=1.0, weight=3) line = folium.PolyLine(locations=coords, color='r', **kw) else: zcolors = ['r', 'g', 'c', 'b', 'm'] line = folium.features.ColorLine( coords, #list(zip(lat, lon)), colors=z, colormap=cm.LinearColormap(zcolors, vmin=2, vmax=5), weight=3) m.add_child(line) # add markers for start and end folium.Marker(coords[0], icon=folium.Icon(color='green')).add_to(m) folium.Marker(coords[-1], icon=folium.Icon(color='black')).add_to(m) m.save('./app/static/maps/{0}.html'.format(activity_id)) return
def add_volume_polylines(self): '''add volume polylines to volume heatmap and overwrite self.volume_map ''' mapa = self.get_map('volume_map') df = self.get_frame('volumes') color_map = cm.LinearColormap(colors=['green', 'red'], vmin=df['VOLUME'].min(), vmax=df['VOLUME'].max()) df['volume_lines'] = df.apply(lambda row: self.get_polylines( row['geometry'], row['VOLUME'], row['SECNAME']), axis=1) df = df.sort_values(by='VOLUME', ascending=False) for points in df['volume_lines'].tolist(): locations = [] colors = [] tooltip = points[0][2] for point in points: loc = point[0] color = point[1] tooltip = point[2] locations.append(loc) colors.append(color) this_line = folium.PolyLine(locations=locations, tooltip=tooltip, color=color_map(color)) this_line.add_to(mapa)
def draw_speed_map(self): '''get speed map, save to file and overwrite self.speed_map ''' mapa = self.get_map('speed_map') df = self.get_frame('speeds') color_map = cm.LinearColormap(colors=['yellow', 'red'], vmin=df['SPEED'].min(), vmax=df['SPEED'].max()) df['speed_lines'] = df.apply(lambda row: self.get_polylines( row['geometry'], row['SPEED'], row['STREET_NAME']), axis=1) df = df.sort_values(by='SPEED', ascending=False) for points in df['speed_lines'].tolist(): locations = [] colors = [] tooltip = points[0][2] for point in points: loc = point[0] color = point[1] tooltip = point[2] locations.append(loc) colors.append(color) this_line = folium.PolyLine(locations=locations, tooltip=tooltip, color=color_map(color)) this_line.add_to(mapa) mapa.save('./html/speed_map.html') print("map saved")
def color_of_od(origin, destination, color_dict): linear = cm.LinearColormap([rainbow_shades[1], rainbow_shades[0]], vmin=0, vmax=1) inner_max_color = np.max(list(color_dict.values())) color = min(color_dict[(origin, destination)], inner_max_color) return linear(color / inner_max_color)
def draw_map(dset, latlons): stations = dset.unique("station") rms = dset.rms("residual") * Unit.m2mm # Map layers webmap = folium.Map((20, 0), zoom_start=2) # Default is OpenStreetMap folium.TileLayer("Stamen Toner").add_to(webmap) folium.TileLayer("CartoDB Positron").add_to(webmap) # Colors colors = colormap.LinearColormap(("green", "yellow", "red"), vmin=rms / 2, vmax=rms * 2) colors.caption = "RMS [mm]" webmap.add_child(colors) # Stations stations_layer = folium.FeatureGroup(name="Stations") for sta in stations: idx = dset.filter(station=sta) rms = dset.rms("residual", idx=idx) * Unit.m2mm other_idx = [dset.filter(idx=idx, station=other) for other in stations] others = [ f"{dset.rms('residual', idx=i) * Unit.m2mm:.3f} mm to {other} ({sum(i)})" for i, other in zip(other_idx, stations) if other != sta and any(i) ] popup = f"<b>{sta}</b> ({sum(idx)}): {rms:.3f} mm<br />{'<br />'.join(others)}" stations_layer.add_child( folium.CircleMarker( latlons[sta], popup=popup, fill=True, color=colors(rms), radius=max(5, 10 * np.sqrt(np.mean(idx) * len(stations))), )) webmap.add_child(stations_layer) # Baselines for sta_1 in stations: baseline_layer = folium.FeatureGroup(name="{sta_1} baselines") for sta_2 in stations: idx = dset.filter(station=sta_1) & dset.filter(station=sta_2) if sta_1 == sta_2 or not any(idx): continue rms = dset.rms("residual", idx=idx) * Unit.m2mm locations = [latlons[s] for s in (sta_1, sta_2)] popup = "<b>{sta_1} - {sta_2}</b> ({sum(idx)}): {rms:.3f} mm" baseline_layer.add_child( folium.PolyLine(locations, popup=popup, color=colors(rms), weight=max(1, 2 * np.mean(idx) * len(stations)**2))) if baseline_layer._children: webmap.add_child(baseline_layer) folium.LayerControl().add_to(webmap) return webmap
def colormap_alpha(existing): '''Adds alpha channel from 1 to 0 to existing colormap''' new_colors = [] for i, (r, g, b, a) in enumerate(existing.colors): new_a = i / (len(existing.colors) - 1) new_colors.append((r, g, b, new_a)) return cm.LinearColormap(colors=new_colors, vmin=existing.vmin, vmax=existing.vmax)
def createHeatmap(map,data,x,y): # Add heatmap Legend cm1 = cm.LinearColormap(['b','c','lime','y','r'], vmin=0, vmax=1, caption='Heatmap Legend') map.add_child(cm1) # List comprehension to make out list of lists heat_data = [[row[y],row[x]] for index, row in data.iterrows()] # Plot it on the map HeatMap(heat_data,name = 'Heat Map',radius = 25,gradient = {0.1: 'blue',0.25: 'cyan', 0.5: 'lime',0.75:'yellow',0.9:'orange', 1: 'red'}).add_to(map)
def create_color_map(values, color_map_name): """Create a color map to use with a geojson layer.""" vals = [i for _, i in values.items()] linear = cm.LinearColormap( COLOR_MAPS[color_map_name], vmin=min(vals), vmax=max(vals) ) return linear
def color_scale(occ_df): r""" The color_scale function determine a color scale for the circles indicating level of pollution. """ linear = cm.LinearColormap(['green', 'yellow', 'red'], vmin=min(occ_df['standard']), vmax=max(occ_df['standard'])) return (linear)
def mkColorBar(self, name, norm): #linear = bcm.linear.BuPu.to_step(n=len(norm),data=norm,method="quantiles",round_method="int") linear = bcm.LinearColormap(self.colors, vmin=norm[0], vmax=norm[-1]) linear = linear.to_step(n=6, data=norm, method='quantiles', round_method='int') linear.caption = name return linear
def test_max_labels_linear(max_labels, expected): colorbar = cm.LinearColormap(['red'] * 10, vmin=0, vmax=9, max_labels=max_labels) try: colorbar.render() except AssertionError: # rendering outside parent Figure raises error pass assert colorbar.tick_labels == expected
def add_to_map(lat_lon, ratio, world_map): minima = min(ratio) maxima = max(ratio) test = cm.LinearColormap(['red', 'blue'], vmin=minima, vmax=maxima) colorline = folium.ColorLine(lat_lon, ratio, colormap=test, nb_steps=len(lat_lon), weight=4, opacity=1) world_map.add_child(colorline)
def get_color_map_log(count_df): log_count = pd.np.log10(count_df[count_df['count'] != 0]['count']) vmax = log_count.max() colormap = cm.LinearColormap(colors=['white', 'yellow', 'red'], vmin=0, vmax=vmax) #index=count_df['count'].quantile([0,.2,.4,.6,.8,1.0] #colormap = colormap.to_step(n=4,index=[0,100,1000,5000,10000,26825]) #colormap = colormap.to_step(n=100, data=log_count, method='quantiles') return colormap
def part_1(data): # These are the users we are interested in users = [75027, 102829] users_data = data.loc[data['User_ID'].isin(users)] users_data['timestamp'] = 0 # Convert the date to a timestamp so it may be visualised users_data['timestamp'] = users_data['date'].apply(lambda x: time.mktime( datetime.datetime.strptime(x, '%d/%m/%Y').timetuple()) - np.min( users_data['timestamp'])) # Dict to store user geoms user_points = {} # Loop through users and store their [lat, lon, timestamp] in the dict for i in users: user_data = users_data.loc[users_data['User_ID'] == i] user_points[i] = [ i for i in zip(user_data['lat'], user_data['lon'], users_data['timestamp']) ] # Set up a colormap so the timestamp can be visualised colormap = cm.LinearColormap(colors=['red', 'blue'], index=[ np.min(users_data['timestamp']), np.max(users_data['timestamp']) ], vmin=np.min(users_data['timestamp']), vmax=np.min(users_data['timestamp'])) # Initialise the map object my_map = Map([np.mean(data['lat']), np.mean(data['lon'])], zoom_start=12.5) # Colour for each user colors = ['green', 'orange'] # Loop through each user in the dict for i, (k, v) in enumerate(user_points.items()): color = colors[i] # Loop through the points/timestamps for p in v: folium.Circle(location=p[0:2], radius=80, fill=True, fill_color=color, color=colormap(p[2]), fill_opacity=1).add_to(my_map) my_map.save('my_map_1_1.html')
def cluster_map(self): ''' Creates and saves a map that shows a cluster of stop lat/lng points that have over 50 data points and assigns them an icon based on their mode of transportation. The icon is also shaded to represent the on-time departure distribution with red being low and green being high. Args: None ''' # Cluster of Stops with On-Time Departure % on_time = self.data.groupby(['stop_id', 'stop_name', 'stop_lat', 'stop_lng', 'route_type']).departure_status.apply(lambda x: (x == 'on_time').sum()).reset_index(name='on_time_stops') total = self.data.groupby(['stop_id', 'stop_name', 'stop_lat', 'stop_lng', 'route_type']).size().reset_index(name='total_stops') map_data = pd.merge(on_time, total, on=['stop_id', 'stop_name', 'stop_lat', 'stop_lng', 'route_type']) map_data['on_time_percent'] = map_data.on_time_stops / map_data.total_stops map_data['on_time_str'] = map_data.on_time_percent.apply(lambda x: f"{x:.1%}") map_data['map_icon'] = map_data.route_type.apply(lambda x: x if x=='bus' else 'train') map_data = map_data[map_data.total_stops >= 50] step = cmp.LinearColormap( ['red', 'yellow', 'green'] ,vmin=round(min(map_data.on_time_percent),2) ,vmax=round(max(map_data.on_time_percent),2) ,caption='On-Time Departure Percentage' ) stops = map_data[['stop_lat', 'stop_lng']] stop_list = stops.values.tolist() icon_list = map_data.map_icon.tolist() on_time_list = map_data.on_time_percent.tolist() name_list = map_data.stop_name.tolist() stop_map = folium.Map(location=[39.7426534, -104.9904138] ,tiles='Stamen Terrain') marker_cluster = plugins.MarkerCluster().add_to(stop_map) for stop in range(0, len(stop_list)): folium.Marker(location=stop_list[stop] ,icon=folium.Icon( color='white' ,icon_color=step(on_time_list[stop]) ,icon=icon_list[stop] ,prefix='fa') ,popup=f"{name_list[stop]}: {on_time_list[stop]:.1%}" ).add_to(marker_cluster) if self.route_label == 'All': stop_map.save(f"html/{self.route_type}_cluster_map.html") else: stop_map.save(f"html/{self.route_label}_cluster_map.html")
def world_map_report(df, month): """ Build a world map """ country_geo = os.path.join('world-countries.json') df.reset_index(inplace=True) map_dict = df.set_index('Country')['Query Count - ' + month].to_dict() color_scale = cl.LinearColormap(['yellow', 'red'], vmin=min(map_dict.values()), index=[0, 2 * 10**7], vmax=max(map_dict.values())) color_legend = cl.LinearColormap(['yellow', 'red'], vmin=min(map_dict.values()), index=[0, 10**7], vmax=10**7) color_legend.caption = 'DNS Query Count - By Source Country - ' + month def get_color(feature): value = map_dict.get(feature['properties']['name']) if value is None: return '#ffffff' # MISSING -> white else: return color_scale(value) m = folium.Map(location=[30, 10], zoom_start=2) m.add_child(color_legend) folium.GeoJson(data=country_geo, style_function=lambda feature: { 'fillColor': get_color(feature), 'fillOpacity': 0.7, 'color': 'black', 'weight': 1, }).add_to(m) m.save(outfile="world_map.html", zoom_start=2)
def map_visulization(location): m = folium.Map(location=[ np.mean([location[i][0] for i in range(len(location))]), np.mean([location[i][1] for i in range(len(location))]) ], zoom_start=13) colorscale = cm.LinearColormap(('r', 'y', 'g'), vmin=0, vmax=20) for l in location: folium.Circle(location=[l[0], l[1]], radius=1, color=colorscale(l[2]), fill=True).add_to(m) colorscale.caption = 'Speed (m/s)' m.add_child(colorscale) m.save('test.html')
def init_db_and_html(db): db.drop_all() db.create_all() houses = pd.read_csv(filename) def colormapper(x): return str(linear(x)) def rand_jitter(arr): stdev = .000001 * (max(arr) - min(arr)) return arr + np.random.randn(len(arr)) * stdev houses["latitude"] = rand_jitter(houses['latitude']) houses["longitude"] = rand_jitter(houses['longitude']) houses["milprice"] = houses["price"] / 1e6 linear = cm.LinearColormap(['green', 'yellow', 'red'], vmin=houses.milprice.min(), vmax=houses.milprice.max()) houses["color"] = houses["milprice"].apply(colormapper) houses["url"] = [ "https://www.boliga.dk/bolig/" + str(i) for i in houses.id.values ] houses = houses[~houses["guid"].isnull()] create_map(houses) hist = pd.read_csv(historical_data) create_hist_plot(hist) for index, row in houses.iterrows(): house = House( guid=row['guid'], price=round(row['milprice'], 2), size=row['size'], expense=row.expense, address=row.street, link=row.url, favorite=False, ) db.session.add(house) db.session.commit()