Hi
I have been looking for solutions to click a country in a Choropleth Map which would open a new window to a country-specific URL.
I have seen examples for JS and for Dash. However, I haven’t seen an example that would work for my Graph Objects with plotly.py
The on_click function sadly doesn’t work for choropleth quite yet.
Any suggestions would be much appreciated!
Thanks!
I am using the Graph Object Plotly.py to create the Plot in my Django backend:
class DataView(ListView):
template_name = 'data/data.html'
model = SBPRI
context_object_name = 'SBPRI'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) # open context data which is sent to frontend
countries = sorted(list(Data.objects.values_list('country', flat=True).distinct())) # get country list from database
iso3s = [] # empty list
for cty in countries:
qs = WorldBorder.objects.filter(name=cty) #queryset of country row
iso3 = qs.values('iso3') #queryset of iso3 in that row
iso3s += [iso3[0]['iso3']] #grab first value (only value) in new qs
#build trendmap monthly with Data Model
figmonth = go.Figure()
category = 'SBPRI'
dates = list(Data.objects.order_by('-date').values_list('date', flat=True).distinct()[0:2])
diff = []
for country in countries:
diff += [str((Data.objects.filter(country=country, date=dates[0], category=category).values_list('value', flat=True)[0] / Data.objects.filter(country=country, date=dates[1], category=category).values_list('value', flat=True)[0] - 1)*100)]
figmonth.add_trace(go.Choropleth(
locations = iso3s, #borders to use
z = diff, #data with clever mapping function to get the data
text = countries, #text when hovering
colorscale='agsunset', #https://plotly.com/python/builtin-colorscales/
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '',
colorbar_title = 'SBPRI<br>Month<br>Trend',
showscale = False,
zmin = -30,
zmax = 30,
customdata = ['https://google.com']
))
figmonth.update_layout(
template='plotly',
autosize=True,
height=600,
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
annotations = [dict(
x=0.55,
y=0.1,
xref='paper',
yref='paper',
text='Source: <a href="">"GG"</a>',
showarrow = False
)]
)
trendmapmonth = plot(figmonth, output_type='div', include_plotlyjs=False, config={'displayModeBar': False, 'displaylogo': False})
context['trendmapmonth'] = trendmapmonth
these are the suggestions I have found but couldnt get to work: