2012-11-15 2 views
15

안녕하세요, 특정 색으로 채워진 일부 국가의 파이썬베이스 맵을 사용하여지도를 플롯하려고합니다.파이썬 기본지도에 나라를 채우십시오

거기 밖으로 빠르고 쉬운 해결책 있는가?

+2

아마 유용 : HTTP : //www.geophysique./2011/01/27/matplotlib-basemap-tutorial-07-shapefiles-unleached/ – unutbu

+0

나는 이것을 돕는다. http://matplotlib.1069221.n5.nabble.com/How-to-draw-a-specific- country-by-basemap-td15744.html –

+2

이러한 의견을 보내 주셔서 감사합니다. 나는 또한 내가 찾고 있던 자유 국가 데이터가있는 사이트를 발견했다. [http://www.naturalearthdata.com/](http://www.naturalearthdata.com/) –

답변

12

@unutbu가 이미 말했듯이, Thomas의 게시물 here은 정확히 당신이 쫓고있는 것입니다.

import cartopy.crs as ccrs 
import matplotlib.pyplot as plt 
import cartopy.io.shapereader as shpreader 
import itertools 
import numpy as np 

shapename = 'admin_0_countries' 
countries_shp = shpreader.natural_earth(resolution='110m', 
             category='cultural', name=shapename) 

# some nice "earthy" colors 
earth_colors = np.array([(199, 233, 192), 
           (161, 217, 155), 
           (116, 196, 118), 
           (65, 171, 93), 
           (35, 139, 69), 
           ])/255. 
earth_colors = itertools.cycle(earth_colors) 



ax = plt.axes(projection=ccrs.PlateCarree()) 
for country in shpreader.Reader(countries_shp).records(): 
    print country.attributes['name_long'], earth_colors.next() 
    ax.add_geometries(country.geometry, ccrs.PlateCarree(), 
         facecolor=earth_colors.next(), 
         label=country.attributes['name_long']) 

plt.show() 

output

+3

이 사이트의 답변에 필수 부분을 게시하거나 게시 위험을 삭제해야합니다. [링크보다 간신히 답을 제시하는 FAQ를 참조하십시오.] (http : // stackoverflow .com/faq # deletion) 원하는 경우 링크를 포함 할 수 있지만 '참조'로만 사용하십시오. 대답은 링크가 필요없이 독자적으로 서 있어야합니다. – Taryn

+1

고마워요 @bluefeet - 나는 그것이 왜 그런지 알 수 있습니다. 나는 새로운 정보를주기 위해 해답을 업데이트했다. (내가 저작권을 가지고 있지 않은 원래의 링크를 복제하지 않고). 건배, – pelson

+0

shpreader.natural_earth를 호출하면 http 404 찾을 수 없음 오류가 발생합니다. 다운로드하려고 시도한 것 같습니다. – Leo

9

pelson의 대답에 의해 영감을, 내가 포스트 :

당신은 약간 http://scitools.org.uk/cartopy/docs/latest/tutorials/using_the_shapereader.html에서 적용 할 수 있습니다 (v0.7)에 Cartopy, 해당 코드로이 작업을 수행 할 수 있어야 내가 가진 해결책. 나는 최선을 다하는 당신에게 맡길 것이므로, 지금은 어떤 대답도 받아들이지 않을 것입니다.)

#! /usr/bin/env python 

import sys 
import os 
from pylab import * 
from mpl_toolkits.basemap import Basemap 
import matplotlib as mp 

from shapelib import ShapeFile 
import dbflib 
from matplotlib.collections import LineCollection 
from matplotlib import cm 

def get_shapeData(shp,dbf): 
    for npoly in range(shp.info()[0]): 
    shpsegs = [] 
    shpinfo = [] 

    shp_object = shp.read_object(npoly) 
    verts = shp_object.vertices() 
    rings = len(verts) 
    for ring in range(rings): 
     if ring == 0: 
      shapedict = dbf.read_record(npoly) 
     name = shapedict["name_long"] 
     continent = shapedict["continent"] 
     lons, lats = zip(*verts[ring]) 
     if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: 
      raise ValueError,msg 
     x, y = m(lons, lats) 
     shpsegs.append(zip(x,y)) 
     shapedict['RINGNUM'] = ring+1 
     shapedict['SHAPENUM'] = npoly+1 
     shpinfo.append(shapedict) 

    lines = LineCollection(shpsegs,antialiaseds=(1,)) 
    lines.set_facecolors(cm.jet(np.random.rand(1))) 
    lines.set_edgecolors('k') 
    lines.set_linewidth(0.3) 
    ax.add_collection(lines) 


if __name__=='__main__': 

    f=figure(figsize=(10,10)) 
    ax = plt.subplot(111) 
    m = Basemap(projection='merc',llcrnrlat=30,urcrnrlat=72,\ 
      llcrnrlon=-40,urcrnrlon=50,resolution='c') 
    m.drawcountries(linewidth=0.1,color='w') 

    sfile = 'ne_10m_admin_0_countries' 

    shp = ShapeFile(sfile) 
    dbf = dbflib.open(sfile) 
    get_shapeData(shp,dbf) 

    show() 
    sys.exit(0) 

다음은 올바른 색상 (매우 우아하지 내가 아는)에서 알바니아를 입력하는 방법을 내 예입니다 결과

example for filling in countries in different colours

입니다.

#HACK for Albania 
    shpsegs = [] 
    shpinfo = [] 

    shp_object = shp.read_object(9) 
    verts = shp_object.vertices() 
    rings = len(verts) 
    for ring in range(rings): 
     if ring == 0: 
      shapedict = dbf.read_record(9) 
     name = shapedict["name_long"] 
     continent = shapedict["continent"] 
     lons, lats = zip(*verts[ring]) 
     if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: 
      raise ValueError,msg 
     x, y = m(lons, lats) 
     shpsegs.append(zip(x,y)) 
     shapedict['RINGNUM'] = ring+1 
     shapedict['SHAPENUM'] = npoly+1 
     shpinfo.append(shapedict) 
    lines = LineCollection(shpsegs,antialiaseds=(1,)) 
    if name == 'Albania': 
    lines.set_facecolors('w') 
    lines.set_edgecolors('k') 
    lines.set_linewidth(0.3) 
    ax.add_collection(lines) 

다른 모든 모양을 수행 한 후에는이 작업을 수행하는 것이 중요합니다. 아마 당신은이 코드의 일부를 제거 할 수 있지만, 나는 그것이 충분하다고 말했다. 이름이나 대륙으로 내 응용 프로그램 I 색 contries에 대한

따라서이 라인 :이 웹 사이트에서 가져온 사용

name = shapedict["name_long"] 
    continent = shapedict["continent"] 

데이터 : http://www.naturalearthdata.com/

+2

알바니아가 침몰했습니다. 많은 사람들이 알아 차릴 것입니다 : D – theta

+0

예, 실제로 아르메니아와 마찬가지입니다. 나중에 두 나라를 명시 적으로 채워서 일자리를 찾아야했습니다.naturalearthdata에서 온 사람들과의 inquiery는 결정적인 것이 아니었고, 일단 나를 위해 그것을 고치면 이것을 따라 가지 않았습니다. –

+0

@red_tiger 아르헨티나와 아르헨티나와 같은 문제가 있습니다. "알바니아 문제"에 해결책을 게시 할 수 있습니까? NaturalEarth의 사람들은 뭐라고 말했습니까? 감사. –