为什么Python文森特地图可视化不从数据帧映射数据?

2024-10-01 09:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用这个包Pythonvincent地图可视化。我在ipython notebook工作。在

我用国家FIPS代码(取自here)定义了简单的pandasDataFrame。然后我试图用这些FIPS代码用vincent映射DataFrame数据,但结果显示的结果无法以任何方式给国家着色。我该怎么做?在

country_data_tmp = pd.DataFrame({'country_names' : np.array(['Argentina', 'Armenia', 'Australia', 'Austria']),
                                 'country_FIPS' : np.array(['032', '051', '036', '040']),
                                 'my_rate' : np.array([0.254, 0.3456, 0.26, 0.357])})
country_data_tmp.head()

enter image description here

^{pr2}$

enter image description here


Tags: 代码dataframedatahere可视化ipythonnp地图
1条回答
网友
1楼 · 发布于 2024-10-01 09:19:06

它们不会显示,因为您没有正确设置map_keyworld_countries.topo.json文件通过3个字母的代码标识国家,在该文件中命名为id(这对应于page you linked to中名为alpha-3的字段)。如果您查看the raw data in that json file,可以看到这一点。在

另外,在geo_data中设置'name': 'countries',但在map_key中,您尝试将其引用为counties(注意缺少的r)。很容易犯错误,因为在示例页面中,counties是他们绘制美国县地图的地方。在

如果您更改变量名以使它们引用非空字段-您将得到一个可爱的映射,即数据表中的country_alpha3与JSON变量countries中的id匹配。在

N.B.根据您的代码,只有您有数据的国家才会被绘制出来。如果您希望所有国家的轮廓都被勾勒出来,那么可以添加一个图层,其中所有国家的轮廓都是per the second example here,但是只有那些数据是彩色的。我已经在下面的第二个代码/输出部分中提供了代码更改。在

N.B.2当前值为my_rate,颜色对比度不是很明显。试着用[0,0.3,0.7,1.0]让自己相信这是用不同的颜色。在

代码

#Data setup bit - Input[1] from your notebook
#Note new name for country code country_alpha3

import pandas as pd
import numpy as np

country_data_tmp = pd.DataFrame({'country_names' : np.array(['Argentina', 'Armenia', 'Australia', 'Austria']),
                                 'country_alpha3' : np.array(['ARG','ARM','AUS','AUT']),
                                 'my_rate' : np.array([0.254, 0.3456, 0.26, 0.357])})
country_data_tmp.head()

#map drawing bit Input[2] from your notebook
#Note the changes in variable names

world_topo = r'world-countries.topo.json'

geo_data = [{'name': 'countries',
             'url': world_topo,
             'feature': 'world-countries'}]

vis = vincent.Map(data=country_data_tmp, 
                  geo_data=geo_data, 
                  scale=1100, 
                  data_bind='my_rate', 
                  data_key='country_alpha3',
                  map_key={'countries': 'id'})

vis.display()

输出

Output of script with sample data

带轮廓层和数据层的代码(对于有数据的代码为彩色):

^{pr2}$

输出(输出层加数据层)

Image with countries outlined - those with data coloured

相关问题 更多 >