Hướng dẫn choropleth map python folium - bản đồ choropleth trăn lá

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
2 là thư viện
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
3 cho trực quan hóa dữ liệu không gian địa lý tương tác. Nó là một trình bao bọc của thư viện JavaScript
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
4. Bạn có thể đọc thêm về nó trong phần Bản đồ của bộ sưu tập.

Khởi tạo bản đồ

Một bản đồ được tạo bằng

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
2 luôn bắt đầu với bước khởi tạo trong đó gạch và vị trí được xác định:

# import the folium library
import folium

# initialize the map and store it in a m object
m = folium.Map(location=[40, -95], zoom_start=4)

# show the map
m

Làm cho máy tính xách tay này được tin tưởng để tải bản đồ: Tệp -> Notebook tin cậy

Bây giờ, chúng ta đang ở đây, chúng ta hãy hiển thị các trạng thái với một số màu sắc thích hợp để có được lục lạp.

Dữ liệu

Để xây dựng bản đồ choropleth, bạn cần 2 đầu vào dữ liệu:

  • một tập hợp các vùng địa lý và tọa độ ranh giới của chúng
  • giá trị số cho từng khu vực, được sử dụng cho màu

BlogPost này dựa trên tài liệu chính thức và nhằm mục đích hình dung tỷ lệ thất nghiệp ở Hoa Kỳ. Hãy tải dữ liệu 2:

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)

Choropleth của Hoa Kỳ

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m

Làm cho máy tính xách tay này được tin tưởng để tải bản đồ: Tệp -> Notebook tin cậy

Bây giờ, chúng ta đang ở đây, chúng ta hãy hiển thị các trạng thái với một số màu sắc thích hợp để có được lục lạp.

Dữ liệu

Để xây dựng bản đồ choropleth, bạn cần 2 đầu vào dữ liệu:

m.save('../../static/interactiveCharts/292-choropleth-map-with-folium.html')

Cách tạo chooropleths với các cấu trúc dữ liệu khác nhau trong Python

Một hợp xướng của các căn hộ cho thuê có sẵn ở NYC, tháng 4 năm 2019 (GitHub)

Bản đồ choropleth được sử dụng để hiển thị các biến thể trong dữ liệu trên các khu vực địa lý (giáo dục dân số). Tôi đã sử dụng choropleths để hiển thị số lượng căn hộ cho thuê có sẵn trên các mã zip ở thành phố New York và để hiển thị số lượng giao dịch thế chấp trên mỗi mã zip trong một khoảng thời gian nhất định. Thư viện Folium của Python cho phép người dùng xây dựng nhiều loại bản đồ tùy chỉnh, bao gồm cả choropleths, bạn có thể chia sẻ dưới dạng tệp

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
7 với người dùng bên ngoài không biết viết mã.horopleth maps are used to show the variations in data over geographic regions (Population Education). I’ve used choropleths to show the number of available rental apartments across ZIP Codes in New York City and to show the number of mortgage transactions per ZIP Code over a given period. Python’s Folium library enables users to build multiple kinds of custom maps, including choropleths, which you can share as
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
7 files with external users who do not know how to code.

Đang tải và xem xét dữ liệu địa lý

Các trang web của chính phủ Hoa Kỳ thường có các tệp dữ liệu địa lý cần thiết để tạo bản đồ. Trang web của NYC, Opendata và trang web của Cục điều tra dân số Hoa Kỳ có các tệp ranh giới địa lý có sẵn trong nhiều kiểu dữ liệu. Python cho phép bạn tải nhiều tệp filetypes, bao gồm các tệp và shapefiles Geojson (

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
8) (
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
9). Các tệp này chứa các ranh giới không gian của một vị trí nhất định.

Tài liệu Folium sườn cho phương pháp

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
0 nói rằng tham số
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
1 chấp nhận hình học Geojson như một chuỗi để tạo bản đồ, đường dẫn, đường dẫn tệp hoặc dữ liệu (JSON, DIRT, GeoPandas, v.v.) cho địa lý địa lý của bạn (tài liệu folium). Bất kể chúng tôi tải tệp như thế nào, chúng tôi phải chuyển đổi dữ liệu hình học để hoạt động đúng với phương pháp này. Tham số
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 của phương pháp này liên kết dữ liệu cho từng vị trí cụ thể (dữ liệu Geojson) với dữ liệu cho vị trí đó (nghĩa là dân số).
geometries” (Folium documentation). No matter how we load the file we must convert the geometry data to function properly with this method. The
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 parameter of this method binds the data for each specific location (GeoJSON data) with the data for that location (i.e. population).

Geojson

Các tệp Geojson lưu trữ các hình dạng hình học, trong trường hợp này là ranh giới của một vị trí và các thuộc tính liên quan của nó. Chẳng hạn, mã để tải tệp Geojson với ranh giới của mã ZIP NYC (được tham chiếu ở trên) như sau:

# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)

Biến

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
3 chứa một từ điển có ít nhất hai khóa, trong đó một trong các khóa được gọi là
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
4, khóa này đang giữ một danh sách từ điển trong đó mỗi từ điển đại diện cho một vị trí. Đoạn trích cấu trúc Geojson chính với vị trí đầu tiên là bên dưới:

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}

Tham số

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 của phương thức
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
0 yêu cầu người dùng tham chiếu khóa chỉ mục duy nhất trong từ điển vị trí trong tệp Geojson dưới dạng chuỗi:

key_on (chuỗi, không có mặc định) - Biến trong tệp Geo_data Geojson để liên kết dữ liệu với. Phải bắt đầu với ‘tính năng, và trong ký hiệu phản đối JavaScript. Ex: ‘Tính năng.id, hoặc‘ Tính năng.ProperIES.statename. (string, default None) — Variable in the geo_data GeoJSON file to bind the data to. Must start with ‘feature’ and be in JavaScript objection notation. Ex: ‘feature.id’ or ‘feature.properties.statename’.

Trong trường hợp trên, khóa chỉ mục là mã zip, dữ liệu liên kết với mỗi vị trí cũng phải có khóa hoặc cột chỉ mục mã zip. Tham số

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 cho ví dụ trên sẽ là chuỗi sau:

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
8

Lưu ý: Phần đầu tiên của chuỗi phải luôn là từ số ít

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
9, nó không giống như từ điển cha mẹ giữ danh sách của từng từ điển vị trí riêng lẻ.

Tham số

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 đang truy cập khóa
m.save('../../static/interactiveCharts/292-choropleth-map-with-folium.html')
1 của từng vị trí cụ thể. Khóa
m.save('../../static/interactiveCharts/292-choropleth-map-with-folium.html')
1 đang giữ một từ điển với mười một phím, trong trường hợp này, khóa
m.save('../../static/interactiveCharts/292-choropleth-map-with-folium.html')
3 là giá trị chỉ mục sẽ liên kết hình dạng hình học với bất kỳ giá trị nào chúng ta muốn vẽ.

Geopandas

Một cách khác để tải dữ liệu địa lý là sử dụng Thư viện GeoPandas Python (Link). Thư viện này rất hữu ích khi tải Shapefiles, được cung cấp trên trang web điều tra dân số của Hoa Kỳ (các tệp ranh giới bản đồ - ShapeFile). GeoPandas hoạt động tương tự như gấu trúc, chỉ có nó mới có thể lưu trữ và thực hiện các chức năng trên dữ liệu hình học. Chẳng hạn, mã để tải Shapefile với ranh giới của tất cả các tiểu bang của Hoa Kỳ như sau:

# Using GeoPandasimport geopandas as gpd
usmap_gdf = gpd.read_file('cb_2018_us_state_500k/cb_2018_us_state_500k.shp')
Đầu của DataFrame USMAP_GDF

Nếu bạn gọi cột hình học hàng đầu tiên (Mississippi) trong Notebook Jupyter, bạn sẽ thấy như sau:

m.save('../../static/interactiveCharts/292-choropleth-map-with-folium.html')
4

Khi một giá trị hình học cụ thể được gọi, bạn sẽ thấy hình ảnh hình học thay vì chuỗi đại diện cho ranh giới của hình dạng, ở trên là giá trị hình học cho hàng đầu tiên (Mississippi)

Không giống như nội dung của từ điển Geojson, không có khóa

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
4 với từ điển bên trong để truy cập và không có cột
m.save('../../static/interactiveCharts/292-choropleth-map-with-folium.html')
1. Tham số
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 của phương thức
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
0 vẫn yêu cầu phần đầu tiên của chuỗi là
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
9, tuy nhiên thay vì tham chiếu từ điển vị trí Geojson, phương thức này sẽ được tham chiếu các cột trong khung dữ liệu địa lý. Trong trường hợp này, tham số ____22 sẽ bằng
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
1, trong đó
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 là cột chứa các mã trạng thái duy nhất sẽ liên kết dữ liệu của chúng tôi với ranh giới địa lý. Cột
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 có số không hàng đầu, California
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 là
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
5. Bạn cũng có thể sử dụng cột
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
6 làm chỉ mục, đảm bảo bạn phù hợp với cả hai cột được sử dụng, định dạng và loại dữ liệu.

Xem xét dữ liệu dân số cho một choropleth

Dữ liệu địa lý và dữ liệu liên quan đến sơ đồ có thể được lưu trữ dưới dạng hai biến riêng biệt hoặc tất cả cùng nhau. Điều quan trọng là theo dõi các loại dữ liệu của các cột và để đảm bảo cột chỉ mục (

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2) giống nhau cho dữ liệu địa lý và dữ liệu liên quan cho vị trí.

Tôi đã truy cập cuộc khảo sát cộng đồng (Liên kết) của Hoa Kỳ và các bảng ước tính và dự báo dân số (liên kết) của Hoa Kỳ để có được dữ liệu dân số và nhân khẩu học từ năm 2019 đến năm 2021. Trưởng phòng của DataFrame như sau:

Người đứng đầu của DataFrame điều tra dân số Hoa Kỳ

Tôi đã lưu dữ liệu dưới dạng tệp

# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
8, trong một số trường hợp, điều này sẽ thay đổi các kiểu dữ liệu của các cột; Ví dụ, chuỗi có thể trở thành giá trị số. Các kiểu dữ liệu khi
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
9i được gọi là như sau:

Các loại dữ liệu cho dữ liệu điều tra dân số trước và sau khi lưu và tải khung dữ liệu dưới dạng tệp CSV

Một điều quan trọng khác cần lưu ý là tất cả các số không hàng đầu trong cột

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
0 không xuất hiện sau khi tải khung dữ liệu. Điều này sẽ phải được sửa chữa; ID phải khớp và là cùng loại dữ liệu (nghĩa là nó không thể là một số nguyên trong một khung dữ liệu và một chuỗi trong một loại khác).

Bản đồ chooropleth cơ bản năm cách khác nhau

Như đã thảo luận ở trên, Folium cho phép bạn tạo bản đồ bằng cách sử dụng các kiểu dữ liệu địa lý, bao gồm Geojson và GeoPandas. Các kiểu dữ liệu này cần được định dạng để sử dụng với thư viện folium và nó luôn luôn trực quan (ít nhất là với tôi) tại sao một số lỗi nhất định xảy ra. Các ví dụ sau đây mô tả cách chuẩn bị cả dữ liệu địa lý (trong trường hợp này là ranh giới trạng thái của Hoa Kỳ) và dữ liệu âm mưu liên quan (dân số của các quốc gia) để sử dụng phương pháp

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
0.

Phương pháp 1: Với Pandas và Geojson, mà không cần chỉ định cột ID

Phương pháp này gần giống nhất với tài liệu ví dụ về bản đồ choropleth. Phương pháp sử dụng tệp Geojson chứa dữ liệu ranh giới trạng thái và khung dữ liệu gấu trúc để tạo bản đồ.

Khi tôi bắt đầu với một tệp GeoPandas, tôi sẽ cần chuyển đổi nó thành tệp Geojson bằng phương pháp Geopandas. Như một lời nhắc nhở, DataFrame địa lý USMAP_GDF trông giống như:

Đầu của DataFrame USMAP_GDF

Sau đó, tôi áp dụng phương thức

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
3 và chỉ định rằng chúng tôi sẽ bỏ
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
4 từ DataFrame, nếu nó tồn tại:

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
5

Lưu ý:

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
6 là biến giữ chuỗi JSON trong kịch bản này

Phương thức này trả về một chuỗi, tôi đã định dạng nó để đọc và hiển thị dễ dàng hơn cho bộ tọa độ đầu tiên bên dưới:

'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'

Lưu ý: Từ điển của các thuộc tính của người Viking không có khóa gọi là id id ”

Bây giờ chúng tôi đã sẵn sàng để kết nối biến JSON mới được tạo với dữ liệu điều tra dân số Hoa Kỳ thu được trong phần trước, người đứng đầu dưới đây:

Người đứng đầu của DataFrame điều tra dân số Hoa Kỳ, được gọi là all_states_census_df bên dướiall_states_census_df below

Sử dụng phương thức Folium từ

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
7, chúng tôi tạo đối tượng bản đồ:

Mã để tạo
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
8

Tham số

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
1 được đặt thành biến
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
6 mới được tạo và tham số
# Using GeoPandasimport geopandas as gpd
usmap_gdf = gpd.read_file('cb_2018_us_state_500k/cb_2018_us_state_500k.shp')
1 được đặt thành DataFrame all_states_cenSus_df. Vì không có ID nào được chỉ định khi tạo biến Geojson, tham số
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 phải tham chiếu một khóa cụ thể từ geodata và nó hoạt động giống như một từ điển (‘Geoid, là giá trị của khóa‘ Thuộc tính). Trong trường hợp này, khóa
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 giữ mã trạng thái kết nối dữ liệu ranh giới hình học trạng thái với dữ liệu điều tra dân số tương ứng của Hoa Kỳ trong ALL_STATE_CENSUSUS_DF DataFrame. Choropleth dưới đây:all_states_census_df dataframe. As no id was specified when creating the GeoJSON variable the
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 parameter must reference a specific key from the geodata, and that it works like a dictionary (‘GEOID’ is a value of the ‘properties’ key). In this case the
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 key holds the state code which connects the state geometric boundary data to the corresponding US Census data in the all_states_census_df dataframe. The choropleth is below:

Kết quả choropleth từ phương pháp trên

Phương pháp 2: Với Pandas và Geojson và chỉ định cột ID

Quá trình này gần như chính xác như trên ngoại trừ một chỉ mục sẽ được sử dụng trước khi gọi phương thức

{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
3.

DataFrame ____65 không có chỉ mục trong ví dụ trên, để sửa điều này, tôi sẽ đặt chỉ mục thành cột

# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 và sau đó gọi ngay phương thức
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
3:

# Using GeoPandasimport geopandas as gpd
usmap_gdf = gpd.read_file('cb_2018_us_state_500k/cb_2018_us_state_500k.shp')
8

Chuỗi kết quả, cho đến khi cặp tọa độ đầu tiên cho dữ liệu trạng thái đầu tiên, là bên dưới:

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'

Từ điển thuộc tính của người Viking không còn có khóa

# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
2 vì nó hiện được lưu trữ dưới dạng khóa mới gọi là
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
4 trong từ điển bên ngoài. Bạn cũng nên lưu ý rằng giá trị
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
4 hiện là một chuỗi thay vì số nguyên. Như đã đề cập trước đây, bạn sẽ phải đảm bảo rằng các loại dữ liệu của dữ liệu kết nối là nhất quán. Điều này có thể trở nên tẻ nhạt nếu dẫn đầu và theo dõi các số 0 có liên quan. Để khắc phục sự cố này, tôi tạo một cột mới có tên
'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'
2 từ cột
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
0 trong
'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'
4:

'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'
5

Bây giờ chúng ta có thể tạo Choropleth:

Mã để tạo C
'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'
6

Sự khác biệt giữa mã này và mã được sử dụng trước đây là tham số tham số

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'properties': {'OBJECTID': 1,
'postalCode': '11372',
'PO_NAME': 'Jackson Heights',
'STATE': 'NY',
'borough': 'Queens',
'ST_FIPS': '36',
'CTY_FIPS': '081',
'BLDGpostal': 0,
'@id': 'http://nyc.pediacities.com/Resource/PostalCode/11372',
'longitude': -73.883573184,
'latitude': 40.751662187},
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.86942457284177, 40.74915687096788],
[-73.89143129977276, 40.74684466041932],
[-73.89507143240859, 40.746465470812154],
[-73.8961873786782, 40.74850942518088],
[-73.8958395418514, 40.74854687570604],
[-73.89525242774397, 40.748306609450246],
[-73.89654041085562, 40.75054199814359],
[-73.89579868613829, 40.75061972133262],
[-73.89652230661434, 40.75438879610903],
[-73.88164812188481, 40.75595161704187],
[-73.87221855882478, 40.75694324806748],
[-73.87167992356792, 40.75398717439604],
[-73.8720704651389, 40.753862007052064],
[-73.86942457284177, 40.74915687096788]]]}}, ... ]}
4 chứ không phải
'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'
9. Bản đồ kết quả hoàn toàn giống như trong Phương pháp 1:

Kết quả choropleth từ phương pháp trên

Phương pháp 3: Với bộ sưu tập tính năng Python Python Pandas và Geopandas

Phương pháp này tạo ra một địa lý giống như đối tượng (bộ sưu tập tính năng Python) từ khung dữ liệu địa lý gốc với thuộc tính

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
0.

Tôi đặt chỉ mục của

# Using GeoPandasimport geopandas as gpd
usmap_gdf = gpd.read_file('cb_2018_us_state_500k/cb_2018_us_state_500k.shp')
5 DataFrame (dữ liệu địa lý của Hoa Kỳ) thành cột
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
6, lưu trữ ID trạng thái, với các số 0 hàng đầu, dưới dạng chuỗi:

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
3

Sau đó, tôi đã tạo một cột phù hợp trong

'{"type": "FeatureCollection",
"features": [{"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"GEOID": 28,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235]'
4 DataFrame (dữ liệu điều tra dân số của Hoa Kỳ) bằng cách thêm một số 0 hàng đầu:

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
5

Cuối cùng, tôi đã sử dụng thuộc tính

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
0 của
'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
7 Geopandas DataFrame để có được một bộ sưu tập tính năng Python của các ranh giới trạng thái hình học, được lưu trữ dưới dạng từ điển, tương tự như các phương pháp từ hai phương pháp đầu tiên:

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
8

Một đoạn trích của biến

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
9 dưới đây:

{'type': 'FeatureCollection',
'features': [{'id': '28',
'type': 'Feature',
'properties': {},
'geometry': {'type': 'MultiPolygon',
'coordinates': [(((-88.502966, 30.215235), ...))]

Cuối cùng, chúng tôi tạo ra choropleth:

Mã để tạo thuộc tính C
{'type': 'FeatureCollection',
'features': [{'id': '28',
'type': 'Feature',
'properties': {},
'geometry': {'type': 'MultiPolygon',
'coordinates': [(((-88.502966, 30.215235), ...))]
0

Bản đồ trông giống như các bản đồ từ trên cao, vì vậy tôi đã loại trừ nó.

Phương pháp 4: với cột loại hình học địa lý

Ở đây chúng tôi gắn bó với địa chất. Tôi đã tạo một khung dữ liệu địa lý được gọi là

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
7 kết hợp dữ liệu hình học và dữ liệu điều tra dân số trong một biến:

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
0

Lưu ý: All_States_Census_DF là một dữ liệu gấu trúc của dữ liệu điều tra dân số Hoa Kỳ và USMAP_GDF là một dữ liệu địa lý lưu trữ dữ liệu ranh giới hình học trạng thái.all_states_census_df is a pandas dataframe of US Census data and usmap_gdf is a GeoPandas dataframe storing state geometric boundary data.

Mã để tạo một choropleth với khung dữ liệu địa lý ở bên dưới:

Mã để tạo một choropleth bằng cách sử dụng khung dữ liệu địa lý

Trong ví dụ trên, tham số

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
1 và tham số
# Using GeoPandasimport geopandas as gpd
usmap_gdf = gpd.read_file('cb_2018_us_state_500k/cb_2018_us_state_500k.shp')
1 đều tham chiếu cùng một khung dữ liệu địa lý như thông tin được lưu trữ ở một nơi. Vì tôi đã không đặt một chỉ mục, tham số
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 bằng
# Code to open a .geojson file and store its contents in a variablewith open ('nyczipcodetabulationareas.geojson', 'r') as jsonFile:
nycmapdata = json.load(jsonFile)
1. Ngay cả với địa lý folium yêu cầu tham số
folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=.1,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
2 để hành động như thể nó đang tham khảo một từ điển như đối tượng.

Như trước đây, bản đồ trông giống như những cái từ trên cao, vì vậy tôi đã loại trừ nó.

Phương pháp 5: với loại hình học địa lý và Branca

Ở đây chúng tôi tạo ra một bản đồ phong cách hơn bằng thư viện Branca và các ví dụ Folium, với nó. Bước đầu tiên với Branca, ngoài việc cài đặt nó, là tạo một đối tượng

{'type': 'FeatureCollection',
'features': [{'id': '28',
'type': 'Feature',
'properties': {},
'geometry': {'type': 'MultiPolygon',
'coordinates': [(((-88.502966, 30.215235), ...))]
7:

import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
1

Trong mã trên, chúng tôi truy cập lớp

{'type': 'FeatureCollection',
'features': [{'id': '28',
'type': 'Feature',
'properties': {},
'geometry': {'type': 'MultiPolygon',
'coordinates': [(((-88.502966, 30.215235), ...))]
8. Ở đây chúng ta có thể đặt các màu chúng ta sử dụng và những giá trị nào sẽ sử dụng cho thang màu. Đối với choropleth này, tôi muốn các màu sắc tỷ lệ theo các giá trị dân số thấp nhất và cao nhất trong dữ liệu điều tra dân số Hoa Kỳ. Để đặt các giá trị này, tôi sử dụng các tham số
{'type': 'FeatureCollection',
'features': [{'id': '28',
'type': 'Feature',
'properties': {},
'geometry': {'type': 'MultiPolygon',
'coordinates': [(((-88.502966, 30.215235), ...))]
9 và
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
00 như trên. Nếu tôi bỏ qua việc làm điều này thì các khu vực không có giá trị sẽ được xem xét trong thang màu, kết quả không có các tham số được đặt này ở bên dưới:

Một choropleth Branca mà không có bộ tham số
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
01 và ____102

Khi đối tượng

{'type': 'FeatureCollection',
'features': [{'id': '28',
'type': 'Feature',
'properties': {},
'geometry': {'type': 'MultiPolygon',
'coordinates': [(((-88.502966, 30.215235), ...))]
7 được tạo, chúng ta có thể tạo một choropleth (mã đầy đủ bên dưới):

Tạo một dàn hợp xướng với khung dữ liệu địa lý và thư viện Branca

Tôi đã điều chỉnh các ví dụ trên trang web Folium, để sử dụng khung dữ liệu địa lý

'{"type": "FeatureCollection",
"features": [{"id": "28",
"type": "Feature",
"properties": {"AFFGEOID": "0400000US28",
"ALAND": 121533519481,
"AWATER": 3926919758,
"LSAD": "00",
"NAME": "Mississippi",
"STATEFP": "28",
"STATENS": "01779790",
"STUSPS": "MS"},
"geometry": {"type": "MultiPolygon",
"coordinates": [[[[-88.502966, 30.215235],'
7. Ví dụ cho phép chúng tôi loại trừ các phần (xuất hiện trong suốt) của dữ liệu địa lý không có dữ liệu điều tra dân số liên quan (nếu dân số cho một trạng thái không có màu thì màu trên choropleth sẽ có màu đen trừ khi nó bị loại trừ). Choropleth kết quả dưới đây:

Một hợp xướng được làm bằng Branca và Geopandas

Branca có thể tùy chỉnh nhưng các giải thích về cách sử dụng nó là rất ít. Readme cho các trạng thái kho lưu trữ của nó:

Không có tài liệu nào, nhưng bạn có thể duyệt các ví dụ.

Bạn phải thực hành bằng cách sử dụng nó để làm cho loại bản đồ bạn muốn.

Bản tóm tắt

Folium có thể được sử dụng để tạo các bản đồ thông tin, như choropleths, cho những người có và không có kiến ​​thức mã hóa. Các trang web của chính phủ thường có dữ liệu địa lý cần thiết để tạo ranh giới vị trí cho dữ liệu của bạn cũng có thể được lấy từ các trang web của chính phủ. Điều quan trọng là phải hiểu các kiểu dữ liệu và filetypes của bạn vì điều này có thể dẫn đến sự thất vọng không cần thiết. Các bản đồ này có khả năng tùy biến cao, ví dụ bạn có thể thêm các chú giải công cụ để chú thích bản đồ của mình. Nó thực hành để sử dụng thư viện này đầy đủ tiềm năng.

Kho lưu trữ của tôi cho bài viết này có thể được tìm thấy ở đây. Mã hóa hạnh phúc.