Folium 0.3.0でPython 3.5.2を実行しています。Foliumカスタムポップアップ
データを持つ特定の国をクリックするたびにカスタムポップアップを作成しようとしています。私はポップアップを表示させることができますが、値を動的に渡すことはできません。私はPythonに精通していますが、JSONなどは初めてです。
まずはシリーズオブジェクトfinal_dict
を持っています。さらに、私は国ポリゴンデータセットcountries_reduced.json
を持っています。 example found hereに続いて、データを持つ国の上にマウスを置いたときのハイライト表示を含めるために、また国をクリックするとポップアップを表示するために、私はfolium.GeoJsonテンプレートをハックします。ポップアップ自体は、コード内の行
var html_aaa = $('<div id="html_aaa" style="width: 100.0%; height: 100.0%;">"""+ "{0:.2f}%".format(final_dict[0] * 100) + """</div>')[0];
によって行われているようしかし、これまでのところ、私は、すべて国のために(例えばfinal_dict[0]
)final_dict
からにいくつかの値を渡すだけで管理している、うまく表示します下のスニペット。たとえば、hereに示すように、米国のポップアップは-0.02%
となりますが、0.18%
となります。
クリックした国に対応する値をポップアップに動的に渡す方法はありますか?次のように
私のコードは次のとおりです。
import pandas as pd
import numpy as np
# Data
array = np.array([-0.000247 , 0.00178 , -0.0183 , 0.00831 , 0.0135 , -0.00266 , 0.00461])
final_dict = pd.Series(array, index=['JPN', 'USA', 'ARG', 'DEU', 'SWE', 'FIN' , 'FRA'])
# Create map
import json
import folium
geo_json_data = json.load(open('countries_reduced.json'))
linear = folium.LinearColormap(['red','yellow','green'], vmin=-0.02, vmax=0.02)
linear.to_step(21)
m = folium.Map([0,0], tiles='Mapbox Bright', zoom_start=2)
g = folium.GeoJson(
geo_json_data,
style_function=lambda feature: {
'fillColor': linear(final_dict[feature['id']]),
'color' : 'black',
'weight' : 2,
'dashArray' : '5, 5'
},
).add_to(m)
# Following example provided here: https://github.com/python-visualization/folium/issues/341,
# I overwrite the g_Template
from jinja2 import Template
g._template = Template("""
{% macro script(this, kwargs) %}
var {{this.get_name()}} = {};
var popup_aaa = L.popup({maxWidth: '300'});
var html_aaa = $('<div id="html_aaa" style="width: 100.0%; height: 100.0%;">"""+ "{0:.2f}%".format(final_dict[0] * 100) + """</div>')[0];
popup_aaa.setContent(html_aaa);
{{this.get_name()}}.style = function(feature) {return feature.properties.style;};
{{this.get_name()}}.highlightStyle = function(feature) {return {
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
};
};
{{this.get_name()}}.onEachFeature = function onEachFeature(feature, layer) {
layer.on({
mouseover: function(e) {
e.target.setStyle({{this.get_name()}}.highlightStyle(e.target.feature));
e.target.bindPopup(popup_aaa);},
mouseout: function(e) {
{{this.get_name()}}.geoJson.resetStyle(e.target);
}
});
};
{{this.get_name()}}.geoJson = L.geoJson(
{% if this.embed %}{{this.style_data()}}{% else %}"{{this.data}}"{% endif %},{
style : {{this.get_name()}}.style,
onEachFeature: {{this.get_name()}}.onEachFeature
})
.addTo({{this._parent.get_name()}});
{% endmacro %}
""")
# And draw the map with additions, save
m.add_child(g)
m.add_child(linear)
m.save('map4.html')