简体   繁体   中英

How to add static text in map using Plotly Choropleth Python

I am plotting an Indian map using plotly and geojson file. Now what I want to do is show static values on the Indian States. Currently those values are visible on hover, I want the values to be seen all the time.

This my code:

import pandas as pd
import plotly.graph_objects as go

df = data_state1
fig = go.Figure(data=go.Choropleth(
    geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
    featureidkey='properties.ST_NM',
    locationmode='geojson-id',
    locations=df['ST_NM'].str.title(), # To make lower case to CamelCase
    z=df['odval']/df['count'],
    text= df['ST_NM'].str.title(),

    autocolorscale=False,
    colorscale='Reds',
    marker_line_color='darkgreen',

    colorbar=dict(
        title={'text': "Amount"},
        thickness=35,
        len=1.0,
        bgcolor='rgba(255,255,255,0.6)',

        xanchor='right',
        x=0.0,
        yanchor='bottom',
        y=0.0
    ),
))

fig.update_geos(
    visible=True,
    projection=dict(
        type='conic conformal',
        parallels=[12.472944444, 35.172805555556],
        rotation={'lat': 24, 'lon': 80}
    ),
    lonaxis={'range': [68, 98]},
    lataxis={'range': [6, 38]}
)

fig.update_layout(
    title=dict(
        text="Average Overdue Amount over Total cases ",
        xanchor='center',
        x=0.5,
        yref='paper',
        yanchor='bottom',
        y=0.9,
        pad={'b': 0}
    ),
    margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
    height=850,
    width=750
)

fig.show()

I also tried with geopandas, on that plot, i was able to plot map with colours on the basis of values, but did not find a way to show state names and values.

Code for geopandas is:

fig, ax = plt.subplots(1, figsize=(10, 10))
ax.axis('off')
ax.set_title('ODVal/Cases distribution',
             fontdict={'fontsize': '15', 'fontweight' : '3'})
merged.plot(column='ratio_od_cases',cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0', legend=True)
plt.text(,merged['State_Name'])

I think the easiest way to add text on the map is to use text mode in go.Scattergeo() and specify the latitude and longitude. From the geojson data used, geopandas is used to calculate the center of the state for the text display.

import pandas as pd
import numpy as np
import plotly.graph_objects as go
from urllib import request
import json

url = "https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson"
with request.urlopen(url) as f:
    geo_india = json.load(f)

import geopandas as gpd
df = gpd.read_file(url)

df["lon"] = df["geometry"].centroid.x
df["lat"] = df["geometry"].centroid.y
df['value'] = np.random.randint(5,50,36)

fig = go.Figure(data=go.Choropleth(
    geojson=geo_india,
    featureidkey='properties.ST_NM',
    #locationmode='geojson-id',
    locations=df['ST_NM'].str.title(), # To make lower case to CamelCase
    z=df['value'],
    text= df['ST_NM'].str.title(),
    autocolorscale=False,
    colorscale='Reds',
    marker_line_color='darkgreen',

    colorbar=dict(
        title={'text': "Amount"},
        thickness=35,
        len=1.0,
        bgcolor='rgba(255,255,255,0.6)',

        xanchor='right',
        x=0.0,
        yanchor='bottom',
        y=0.0
    ),
))

fig.update_geos(
    visible=True,
    projection=dict(
        type='conic conformal',
        parallels=[12.472944444, 35.172805555556],
        rotation={'lat': 24, 'lon': 80}
    ),
    lonaxis={'range': [68, 98]},
    lataxis={'range': [6, 38]}
)

fig.add_trace(go.Scattergeo(
    lon=df['lon'],
    lat=df['lat'],
    mode='text',
    #text=df['ST_NM'].str.title(),
    text=['{}<br>{}'.format(k,v) for k,v in zip(df['ST_NM'].str.title(), df['value'])],
    textfont={'color': 'Green'},
    name='',
))

fig.update_layout(
    title=dict(
        text="Average Overdue Amount over Total cases ",
        xanchor='center',
        x=0.5,
        yref='paper',
        yanchor='bottom',
        y=0.9,
        pad={'b': 0}
    ),
    margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
    height=850,
    width=750
)

fig.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM