Colorize polygons in folium - polygon

I want to print some colorized polygons on a map with folium in python and I need some help. The problem I encounter is that I only get a single color for all of my polygons. Here is a part of my code I run in a loop:
import folium
from shapely.geometry import Polygon
def map_color_rsrp(rsrp):
if (int(rsrp) in range(-70, -50)):
return '#10FF00'
elif (int(rsrp) in range(-90, -70)):
return 'green'
elif (int(rsrp) in range(-110, -90)):
return 'blue'
elif (int(rsrp) in range(-130, -110)):
return '#FF7000'
else: # range(-150, -130)
return 'grey'
# create map
grid_map = folium.Map((51.443787, 7.262206), zoom_start=14)
# create FeatureGroups for RSRP & RSRQ
rsrp_grid_fg = folium.FeatureGroup(name="RSRP", overlay=True)
grid_poly_rows = [
[-78.2, [(7.251043000000002, 51.444325000000035), (7.251043000000002, 51.44462500000004), (7.251343000000002, 51.44462500000004), (7.251343000000002, 51.444325000000035)]],
[-89.3, [(7.251343000000002, 51.444325000000035), (7.251343000000002, 51.44462500000004), (7.251643000000002, 51.44462500000004), (7.251643000000002, 51.444325000000035)]],
[-113.7, [(7.251643000000002, 51.44402500000003), (7.251643000000002, 51.444325000000035), (7.2519430000000025, 51.444325000000035), (7.2519430000000025, 51.44402500000003)]],
[-112.3, [(7.251643000000002, 51.444325000000035), (7.251643000000002, 51.44462500000004), (7.2519430000000025, 51.44462500000004), (7.2519430000000025, 51.444325000000035)]],
[-133.7, [(7.2519430000000025, 51.44402500000003), (7.2519430000000025, 51.444325000000035), (7.252243000000003, 51.444325000000035), (7.252243000000003, 51.44402500000003)]]
]
for row in grid_poly_rows:
mean_rsrp = row[0]
rsrp_tooltip_str = str(mean_rsrp)
rsrp_color = map_color_rsrp(mean_rsrp)
style_ = {
'fillColor': rsrp_color,
'color': rsrp_color,
'weight': 1,
'fillOpacity': 0.5}
folium.GeoJson(Polygon(row[1]),
style_function=lambda x: style_,
tooltip=rsrp_tooltip_str
).add_to(rsrp_grid_fg)
rsrp_grid_fg.add_to(grid_map)
# add LayerControl
folium.LayerControl(collapsed=False).add_to(grid_map)
grid_map.save(outfile="grid.html")
I think I got something wrong with the style_function. Any advice is appreciated! Thanks in advance!
Cheers ninjab3s

I made it work! I found this post https://stackoverflow.com/a/53816162/13872164, which explains that the lambda style function is not executed immediately.
The following changes made my code work:
for row in grid_poly_rows:
mean_rsrp = row[0]
rsrp_tooltip_str = str(mean_rsrp)
folium.GeoJson(Polygon(row[1]),
style_function=lambda x, mean_rsrp=mean_rsrp: {
'fillColor': map_color_rsrp(mean_rsrp),
'color': map_color_rsrp(mean_rsrp),
'weight': 1,
'fillOpacity': 0.5},
tooltip=rsrp_tooltip_str
).add_to(rsrp_grid_fg)
Next time Ill dig deeper before I post

Related

when I run the program def update_graphs will no populate. Can anyone see anything small that prevents that function from running?

from jupyter_plotly_dash import JupyterDash
import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table
from dash.dependencies import Input, Output
import base64
import os
import numpy as np
import pandas as pd
from pymongo import MongoClient
from Module import AnimalShelter
username = "username"
password = "password"
animal = AnimalShelter(username, password)
df = pd.DataFrame.from_records(animal.readAll({}))
#########################
# Dashboard Layout / View
#########################
app = JupyterDash('Dash DataTable Only')
image_filename = 'Grazioso Salvare Logo.png' # customer image
encoded_image = base64.b64encode(open(image_filename, 'rb').read())
app.layout = html.Div([
html.Center(html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()))),
html.Center(html.B(html.H1('Kristopher Collis'))),
html.Hr(),
html.Div(
#Radio Items to select the rescue filter options
dcc.RadioItems(
id='filter-type',
),
),
html.Hr(),
dash_table.DataTable(
id='datatable-id',
columns=[
{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns
],
data=df.to_dict('records'),
editable=False,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable=False,
row_selectable="multi",
row_deletable=False,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current= 0,
page_size= 10,
),
html.Hr(),
html.Div(className='row',
style={'display' : 'flex'},
children =[
html.Div(
id='graph-id',
className='col s12 m6'
),
html.Div(
id = 'map-id',
className='col s12 m6'
),
]
),
html.Br(),
html.Hr(),
])
#############################################
# Interaction Between Components / Controller
#############################################
# #callback for Piechart
#app.callback(
Output('graph-id', "children"),
[Input('datatable-id', "derived_viewport_data")])
#fucntion for update_graph
def update_graphs(viewData):
dff = pd.DataFrame.from_dict(viewData)
names = dff['breed'].value_counts().keys().tolist()
values = dff['breed'].value_counts().tolist()
return[
dcc.Graph(
id = 'graph-id',
fig = px.pie(data_frame = dff,values = values,names = names,
color_discrete_sequence = px.colors.sequential.RdBu,width = 800,height = 500
)
)
]
#callback for update_map
#app.callback(
Output('map-id', "children"),
[Input('datatable-id', "derived_viewport_data"),
Input('datatable-id', 'selected_rows'),
Input('datatable-id', 'selected_columns')])
#update_function with variables
def update_map(viewData, selected_rows, selected_columns):
dff = pd.DataFrame.from_dict(viewData)
#width, height of map, center of map, and how much zoom do you want for map
return [dl.Map(style = {'width': '1000px', 'height': '500px'}, center = [30.75,-97.48], zoom = 7,
children = [dl.TileLayer(id = "base-layer-id"),
#marker with tool tip and popup
dl.Marker(position=[(dff.iloc[selected_rows[0],13]), (dff.iloc[selected_rows[0],14])], children=[
dl.Tooltip(dff.iloc[selected_rows[0],4]),
dl.Popup([
html.H4("Animal Name"),
html.P(dff.iloc[selected_rows[0],9]),
])
])
])
]
app
When I run the program, the geoloction map populates but not the graph. I was able to populate the graph a couple of times finding information on plotly, and other documentation. I have spent a while trying to figure out why the graph will not display again. I did attempt to use fig.show() at the bottom of the update_graphs function. I am not sure if that was what made it work, but I am stumped. I am respectfully requesting help finding the error in the def update_graphs function.

Put an append list into a bar graph python

I know how to make a bar graph but I'm trying to put a append two append lists inside of the graph
one is the quantity of a item and the other is the item I would like to know if this is possible and if it is how should I do this. This is what I tried.
itemls = [0]
itemquantityls = [0]
option = 0
while option < 3:
Mainmenue = ["Main menue",
"1. ADD AN ITEM",
"2. GENERATE A CHART",
"3. EXIT"]
for i in (Mainmenue):
print(i)
option = int(input("Option you want:"))
if option == 1:
item = (input("add an item:"))
itemquantity = (input("Item quantity:"))
itemls.append(item)
itemquantityls.append(itemquantity)
elif option == 2:
import matplotlib.pyplot as plt
plt.bar(itemls, itemquantityls)
plt.title('Items and quantity')
plt.xlabel('Item')
plt.ylabel('Item quantity')
plt.show()
elif option == 3:
print("program is teminating")
else:
print("Wrong Input try again")
Thanks in advance. :)

Subgraph doesn't appear in graphviz chart

I can't figure out, why subgraph doesn't work here:
digraph virtPfr {
node [
shape=box
]
Start [
style=rounded,
label="create folder profiles"
]
subgraph asd {
label = "copy files from other profiles"
cpIfDestFilesExist [
label = "Check for file existance"
]
Cp [
label = "Copy"
]
}
Start -> asd
cpIfDestFilesExist -> Start
cpIfDestFilesExist -> Cp
}
but this code works:
digraph G {
node [
shape = "record"
]
Animal [
label = "Animal name and age"
]
subgraph clusterAnimalImpl {
label = "Package animal.tmpl"
Dog [
label = "Dog name and age"
]
Cat [
label = "Cat name and age"
]
}
Dog -> Animal
Cat -> Animal
Dog -> Cat
}
I don't understand, what's different on the top graph, in comparison to the bottom graph, that the bottom works, but the top doesn't. I've already pulled my eyes out. I don't see the problem here.
Please, help
A couple of issues:
Sub-graph names have to start with the keyword cluster.
You can't connect edges directly to a sub-graph, instead you can use the lhead/ltail workaround described here.
For your graph, it could like as follows:
digraph virtPfr {
graph [compound=true]
node [
shape=box
]
Start [
style=rounded,
label="create folder profiles"
]
subgraph cluster_asd {
label = "copy files from other profiles"
cpIfDestFilesExist [
label = "Check for file existance"
]
Cp [
label = "Copy"
]
}
Start -> cpIfDestFilesExist [lhead=cluster_asd]
cpIfDestFilesExist -> Start
cpIfDestFilesExist -> Cp
}
Which generates the following output:

bokeh 0.12.10 not rendering Segments on GMapPlot

I am trying to display line segments on a map using GMapPlot. The lines flashes in red and then disappears, in jupyter notebook. This is my code (some decimals left out):
map_options = GMapOptions(lat=37.88, lng=-122.23, map_type="roadmap", zoom=10)
plot = GMapPlot(
x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options
)
source = ColumnDataSource( data = dict(
y=[ 37.762260 ],
x=[-121.96226],
ym01=[37.762290 ],
xm01=[-121.96189 ]
)
segment = Segment(x0="x", y0="y", x1="xm01", y1="ym01",line_color="green", line_width=100)
plot.add_glyph(source, segment)
plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
output_notebook()
show(plot)
UPDATE This issue is resolved in https://github.com/bokeh/bokeh/pull/8240 which will be part of Bokeh 1.0
I've tried to reproduce with updated code:
from bokeh.io import show
from bokeh.models import GMapOptions, ColumnDataSource
from bokeh.plotting import figure, gmap
map_options = GMapOptions(lat=37.88, lng=-122.23, map_type="roadmap", zoom=10)
plot = gmap(google_api_key=API_KEY, map_options=map_options)
source = ColumnDataSource( data = dict(
y=[ 37.762260 ],
x=[-121.96226],
ym01=[37.762290 ],
xm01=[-121.96189 ]
))
plot.segment(x0="x", y0="y", x1="xm01", y1="ym01",line_color="green", line_width=10, source=source)
show(plot)
And can confirm that the segment does not show up. Slightly changing to show circles does work, so I have to conclude that this is a bug of some sort. Please file a detailed GitHub issue to report this bug.

Groovy GroupBy field with and without white spaces

I have invoices list as below
def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']
I am trying to do groupBy on the above collection with INVOICE_NUMBER and trying to achieve map with INVOICE_NUMBER and lines as values, below code does it
def lines = invoices*.split('\\|').findAll{ it.size()>1 }
def heads = lines.first()
def invoiceMap = lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{ it.INVOICE_NUMBER }
If I print invoiceMap I get what I intended as below map
[INV-Error_Test1:[[LINE:1, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:22],
[LINE:2, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:24]],
INV-Error_Test2:[[LINE:3, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:26],
[LINE:4, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:28,]]
]
But but if the INVOICE_NUMBER has any white spaces with it in the invoices map my code doesnt work. Can someone help me to make my code work with white spaces on INVOICE_NUMBER?
Use a proper CSV parser, rather than rolling your own.
#Grab('com.xlson.groovycsv:groovycsv:1.0')
import static com.xlson.groovycsv.CsvParser.parseCsv
def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']
def data = parseCsv(invoices.drop(1).join('\n'), separator:'|')
def invoiceMap = data.collect().groupBy { it.INVOICE_NUMBER }
Or with a space in the column title:
def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']
def data = parseCsv(invoices.drop(1).join('\n'), separator:'|')
def invoiceMap = data.collect().groupBy { it.'INVOICE NUMBER' }
You just need to quote your name, like this
def invoiceMap = lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{ it.'INVOICE NUMBER' }

Resources