Hel*_*rey 1 python plotly choropleth
我有带有 Country 列的用户数据集,并且想要绘制用户在各个国家/地区的分布图。我将数据集转换为字典,其中键是国家/地区名称,值是国家/地区的频率计数。字典是这样的:
'usa': 139421,
'canada': 21601,
'united kingdom': 18314,
'germany': 17024,
'spain': 13096,
[...]
Run Code Online (Sandbox Code Playgroud)
为了在世界地图上绘制分布,我使用了以下代码:
#Convert to dictionary
counts = users['Country'].value_counts().to_dict()
#Country names
def getList(dict):
return [*dict]
countrs = getList(counts)
#Frequency counts
freqs = list(counts.values())
#Plotting
data = dict(
type = 'choropleth',
colorscale = 'Viridis',
reversescale = True,
locations = countrs,
locationmode = "country names",
z = freqs,
text = users['Country'],
colorbar = {'title' : 'Number of Users'},
)
layout = dict(title = 'Number of Users per Country',
geo = dict(showframe = False)
)
choromap = go.Figure(data = [data],layout = layout)
iplot(choromap,validate=False)
Run Code Online (Sandbox Code Playgroud)
着色错误;它表明所有国家都在 0-20K 范围内,这是错误的。有没有办法来解决这个问题?谢谢
如果无法访问您的完整数据集,这真的很难回答。我建议从这个例子开始:
情节 1:
在这里,您可以简单地替换lifeExp为您的数据,只要您的数据格式正确,一切都应该没问题。在以下代码段中,我为每个国家/地区创建了随机整数来表示您的counts变量。
代码:
import plotly.express as px
import numpy as np
np.random.seed(12)
gapminder = px.data.gapminder().query("year==2007")
gapminder['counts'] = np.random.uniform(low=100000, high=200000, size=len(gapminder)).tolist()
fig = px.choropleth(gapminder, locations="iso_alpha",
color="counts",
hover_name="country", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
fig.show()
Run Code Online (Sandbox Code Playgroud)
情节 2:
让我知道这对你有什么影响。
编辑:对您的数据的建议:
如果您有一个包含国家名称和计数的字典,您可以轻松构建它的数据框并执行左连接来获得:
情节 2:
只需确保您的字典值是列表,并且国家/地区名称的拼写和格式正确。
代码 2:
import plotly.express as px
import numpy as np
import pandas as pd
np.random.seed(12)
gapminder = px.data.gapminder().query("year==2007")
#gapminder['counts'] = np.nan
d = {'United States': [139421],
'Canada': [21601],
'United Kingdom': [18314],
'Germany': [17024],
'Spain': [13096]}
yourdata = pd.DataFrame(d).T.reset_index()
yourdata.columns=['country', 'count']
df=pd.merge(gapminder, yourdata, how='left', on='country')
fig = px.choropleth(df, locations="iso_alpha",
color="count",
hover_name="country", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
fig.show()
Run Code Online (Sandbox Code Playgroud)