import shapefile

# Read shapefile in shift-jis because this is Japanese data.
# Usually shapefile records are written in utf-8 and need not
# to specify the encoding.
# シェープファイルをshift-jisで読み込む。通常は/w{utf-8}で
# 記録されているのでエンコーディングを指定する必要は無い。
sf = shapefile.Reader('GMJ/data/org/all_japan_d_a.shp','r', encoding='shift-jis')
shapes = sf.shapes()
records = sf.records()

# Extract shapes and records in the region because original
# data is too large to plot.
# 元データは描画するには大きすぎるので領域データを抜き出す。
west, east, south, north = 140, 141, 42, 43
idc_region = [i for i, s in enumerate(shapes)
              if west < s.bbox[2] and s.bbox[0] < east and
                 south < s.bbox[3] and s.bbox[1] < north]
shapes_region = [shapes[idx] for idx in idc_region]
records_region = [records[idx] for idx in idc_region]

# Set basemap.
m = Basemap(llcrnrlon=west, llcrnrlat=south,
            urcrnrlon=east, urcrnrlat=north, resolution='i')
m.drawcoastlines(linewidth=0.4)

# Draw shapes.
# In shapefile, multipolygon are recorded so that inside shapes
# are recorded in the direction opposite to the outside shape.
# Therefore it is not required to reverse their order.
# シェープファイルではマルチポリゴンは内側の図形が外側の図形と
# 反対の方向となるよう記録されているので反転させる必要は無い。
for s, r in zip(shapes_region, records_region):
    lons, lats = [], []
    parts = list(s.parts)
    for p0, p1 in zip(parts, parts[1:]+[len(s.points)]):
        lons += [np.nan] + [p[0] for p in s.points[p0:p1]]
        lats += [np.nan] + [p[1] for p in s.points[p0:p1]]

    # Case 1: Fill all the shapes with pink to check if
    #         there is no duplication or lack.
    #         重複や欠損が無いか確認するため全ての図形を
    #         ピンクで塗る。
    plt.fill(lons, lats, color='hotpink', alpha=0.3)

    # Case 2: Fill the shapes with the correspondant colors
    #         in the records (field 2).
    #         レコードの対応する色(フィールド2)で塗る。
    #plt.fill(lons, lats, color='#'+r[2])

    plt.plot(lons, lats, linewidth=0.5, color='gray')
plt.show()