我正在尝试使用plotly绘制印度地图,但无法找到一种方法。下面是我为美国尝试的代码。
import pandas as pd
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv')
df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(lambda x: str(x).zfill(2))
df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(lambda x: str(x).zfill(3))
df_sample['FIPS'] = df_sample['State FIPS Code'] + df_sample['County FIPS Code']
colorscale = ["#f7fbff","#ebf3fb","#deebf7","#d2e3f3","#c6dbef","#b3d2e9","#9ecae1",
"#85bcdb","#6baed6","#57a0ce","#4292c6","#3082be","#2171b5","#1361a9",
"#08519c","#0b4083","#08306b"]
endpts = list(np.linspace(1, 12, len(colorscale) - 1))
fips = df_sample['FIPS'].tolist()
values = df_sample['Unemployment Rate (%)'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values,
binning_endpoints=endpts,
colorscale=colorscale,
show_state_data=False,
show_hover=True, centroid_marker={'opacity': 0},
asp=2.9, title='USA by Unemployment %',
legend_title='% unemployed'
)
fig.layout.template = None
fig.show()
答案 0 :(得分:8)
您使用的数字工厂create_choropleth
方法是deprecated,专门处理美国县。对于其他地图,您需要使用GeoJSON来绘制地图。 Plotly仅随附世界各国和美国各州的GeoJSON数据,因此您必须自己提供印度各州的数据。
就像您的例子一样,让我们绘制截至July 17的每个州的当前活跃COVID-19病例数(这来自indiacovid19.github.io,它会定期存档印度卫生部的数据) 。至于GeoJSON,快速搜索会产生一些GitHub存储库,但对于我们的案例数据而言,似乎大多数都已过时,因为它们不包括Dadra和Nagar Haveli以及Daman和Diu的合并。幸运的是,datameet为印度各邦提供了最新的shapefile,我进行了一些简化以减小尺寸,并使用GeoJSON转换为mapshaper,然后使用{{ 3}}。
现在,如geojson-rewind中所述,我们可以使用plotly express快速使用我们的数据制作一个Choropleth映射:
import pandas as pd
import plotly.express as px
df = pd.read_csv("https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/active_cases_2020-07-17_0800.csv")
fig = px.choropleth(
df,
geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
featureidkey='properties.ST_NM',
locations='state',
color='active cases',
color_continuous_scale='Reds'
)
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
要更好地控制图表,我们可以直接使用图形对象:
import pandas as pd
import plotly.graph_objects as go
df = pd.read_csv("https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/active_cases_2020-07-17_0800.csv")
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['state'],
z=df['active cases'],
autocolorscale=False,
colorscale='Reds',
marker_line_color='peachpuff',
colorbar=dict(
title={'text': "Active Cases"},
thickness=15,
len=0.35,
bgcolor='rgba(255,255,255,0.6)',
tick0=0,
dtick=20000,
xanchor='left',
x=0.01,
yanchor='bottom',
y=0.05
)
))
fig.update_geos(
visible=False,
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="Active COVID-19 Cases in India by State as of July 17, 2020",
xanchor='center',
x=0.5,
yref='paper',
yanchor='bottom',
y=1,
pad={'b': 10}
),
margin={'r': 0, 't': 30, 'l': 0, 'b': 0},
height=550,
width=550
)
fig.show()
答案 1 :(得分:2)
注意:我无法通过情节进行操作,但是我可以在Bokeh中轻松进行操作。 OP专门要求进行密谋,但我仍在发布此答案,以展示如何以其他方式完成。
GeoJSONDataSource
数据模型中from bokeh.models import GeoJSONDataSource
from urllib.request import urlopen
import json
from bokeh.models import GeoJSONDataSource, HoverTool, LinearColorMapper
from bokeh.palettes import Viridis256
from bokeh.plotting import figure
from bokeh.io import output_file, show
import matplotlib.pyplot as plt
from bokeh.io import show, output_notebook
%matplotlib
output_notebook()
# Geojson of India
with urlopen("https://raw.githubusercontent.com/geohacker/india/master/state/india_state.geojson") as response:
geojson = json.load(response)
# Round robin over over 3 colors
# You can set the colors here based on the case count you have per state
for i in range(len(geojson['features'])):
geojson['features'][i]['properties']['Color'] = ['blue', 'red', 'green'][i%3]
# Set the hover to state information and finally plot it
cmap = LinearColorMapper(palette=Viridis256)
TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save"
geo_source = GeoJSONDataSource(geojson=json.dumps(geojson))
p = figure(title='India', tools=TOOLS, x_axis_location=None, y_axis_location=None, width=800, height=800)
p.grid.grid_line_color = None
p.patches('xs', 'ys', fill_alpha=0.7, line_color='black', fill_color='Color', line_width=0.1, source=geo_source)
hover = p.select_one(HoverTool)
hover.point_policy = 'follow_mouse'
hover.tooltips = [('State:', '@NAME_1')]
show(p)
如上面的代码注释所述,您可以将案例信息添加到数据模型中的状态并将其设置为hovertool。这样,当您将鼠标悬停在状态上时,您将看到案件数。实际上,您只需将所需的任何信息添加到数据模型中的状态,然后使用数据模型来呈现它们。
答案 2 :(得分:1)
抱歉,您不能这样做,因为定位模式只有3个值:
“ISO-3” , “USA-states” , “country names”
并且布局的geo只能具有范围-“world” | “usa” | “europe” | “asia” | “frica” | “north america” | “south america”
的7个值。
因此,要获得印度的地块,您需要获得一个亚洲地块,其中要标记印度,但是没有单独的印度和州地块的选择。
data = dict(type = 'choropleth',
locations = ['india'],
locationmode = 'country names',
colorscale= 'Portland',
text= ['t1'],
z=[1.0],
colorbar = {'title' : 'Colorbar Title'})
layout = dict(geo = {'scope': 'asia'})
这种共谋为您提供了带有印度标记的亚洲地图。