6

无法删除问题。请参考问题:根据字典值使用底图对一个国家/地区进行阴影状态

我想绘制墨西哥每个州的数据(某一年的患病人数)。我正在使用 jupyter 笔记本。到目前为止,我已经看到了几个选项和教程,但似乎没有一个明确解释如何绘制一个国家的地图。下面我解释了一些我看到的选项/教程以及为什么它们没有工作(我这样做只是为了争辩说教程不是很直接):

  1. 散景(http://docs.bokeh.org/en/latest/docs/gallery/texas.html)。鉴于 us_counties 在 bokeh.sampledata 中,在教程中绘制了德克萨斯州。但是我在样本数据中没有找到其他国家。

  2. mpl_toolkits.basemap ( http://www.geophysique.be/2011/01/27/matplotlib-basemap-tutorial-07-shapefiles-unleached/ )。虽然我能够导入 shapefile,但我无法运行from shapefile import ShapeFile(ImportError:无法导入名称 ShapeFile)。此外,我无法下载 dbflib 库。

  3. Vincent(为什么 Python Vincent map visuzalization 不映射来自 Data Frame 的数据?)当我从上述教程中的答案运行代码时,没有图像出现(即使我使用了 command vincent.core.initialize_notebook())。

  4. 情节(https://plot.ly/python/choropleth-maps/)。本教程绘制了从 csv 表中导入信息的美国地图(没有其他国家/地区的信息可用)。如果要绘制另一个国家,是否可以制作表格?

探索了这 4 个选项,我发现教程不是很清楚也不是很容易理解。我很难相信在 python 中绘制一个国家的地图是困难的。我认为一定有比过去教程中解释的更简单的方法。

问题是:用python绘制某个国家(任何)地图的最简单(希望是简单)方法是什么?如何?

我已经安装了以下软件包:matplotlib、pyshp、mpl_toolkits.basemap、bokeh、pandas、numpy。我还从http://www.gadm.org/下载了墨西哥的地图

提前致谢。

4

2 回答 2

7

虽然这个问题在目前的形式下似乎无法回答,但我至少会注意到你在使用底图时似乎有问题 - 你不想导入 Shapefile,而只是使用像这样的对象的readshapefile方法来读取它Basemap

m = Basemap(projection='tmerc')
m.readshapefile("/path/to/your/shapefile", "mexican_states")

然后,您将能够通过m.mexican_states(作为数组列表)访问每个州边界的坐标,并通过m.mexican_states_info. 然后,您将需要某种 dict 或 DataFrame,其中包含状态的名称/代码(对应于 in m.mexican_states_info)和您要绘制的值。一个简单的例子可以像这样工作,假设你有一个名为的字典mexican_states_sick_people,看起来像{"Mexico City":123, "Chiapas":35, ...}

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from mpl_toolkits.basemap import Basemap
from shapely.geometry import Polygon
from descartes import PolygonPatch

fig, ax = plt.subplots()

# Set up basemap and read in state shapefile (this will draw all state boundaries)
m = Basemap(projection='tmerc')
m.readshapefile("/path/to/your/shapefile", "mexican_states")

# Get maximum number of sick people to calculate shades for states based on relative number    
max_sick = np.max(mexican_states_sick_people.values())

# Loop through the states contained in shapefile, attaching a PolygonPatch for each of them with shade corresponding to relative number of sick people
state_patches = []
for coordinates, state in zip(m.mexican_states, m.mexican_states_info):
    if state["State_name"] in mexican_states_sick_people.keys():
        shade = mexican_states_sick_people[state["State_name"]]/max_sick       
        state_patches.append(PolygonPatch(Polygon(coordinates), fc = "darkred", ec='#555555', lw=.2, alpha=shade, zorder=4)

 # Put PatchCollection of states on the map
ax.add_collection(PatchCollection(state_patches, match_original=True))

如果您有一个工作状态的 shapefile 并确保您拥有的病人数据集对于每个允许您将数字与shapefile 中的状态标识符(这是shade = ...循环中的行所依赖的 - 在示例中,我使用 shapefile 中的名称作为键访问字典中的 vals)。

希望这有帮助,祝你好运!

于 2016-03-20T19:15:58.743 回答
4

这可能不是您希望的答案,但是您是否看过Plotly 的地图?他们的示例看起来与您想要做的完全一样,尽管我自己并不熟悉,而且我不知道他们有哪些可用的地图以及上传自己的地图有多容易。

于 2016-03-18T17:33:13.403 回答