如何使用 geopandas 将自定义颜色指定为点值?

问题描述 投票:0回答:2

我用 geopandas 制作了一张地图。然而,我使用 geopandas、常规 pandas、matplotlib 和 shapely.geometry 来做不同的事情。我需要自定义地图上的颜色,并将其分配给列中的特定值。更具体地说,我有一列鸟名,并希望每只鸟都有自己的自定义颜色。下面的地图显示了鸟类的观测点。如何为观鸟添加自定义颜色?我会使用 geopandas、pandas 还是其他东西?

import pandas as pd
import geopandas as gpd
import contextily as ctx
import matplotlib.pyplot as plt
from shapely.geometry import Point, Polygon

# Create a new dataframe
france_df = pd.read_csv('bird_tracking.csv')

# Filter the dataset for France latitude and longitude range
france_df = france_df.query('-3 < longitude < 4')
france_df = france_df.query('45 < latitude < 51')

# Designate the right coordinate system (maps can be drawn differently)
crs = 'EPSG:4326'

# Takes the lat and long from our bird sightings, puts into list of single points (shapely)
geometry = [Point(xy) for xy in zip(france_df['longitude'], france_df['latitude'])]

# Create GeoPandas dataframe (includes our France bird tracking data frame)
geo_df = gpd.GeoDataFrame(france_df, crs = crs, geometry = geometry)

# Create figure and map axes, assign to subplot (matplotlib)
fig, ax = plt.subplots(figsize=(15, 15))

# Assign colors to each bird name
bird_palette = {'Boba': 'turquoise', 'Kiwi': 'green', 'Pretzel' : 'brown'}

# Specify France map coordinates and add more formatting
map_france = geo_df.to_crs('EPSG:3857').plot(column='bird_name', linewidth=2, ax=ax, alpha=0.5, legend=True, markersize=10)
ctx.add_basemap(map_france, source=ctx.providers.CartoDB.Positron)

这是原始数据集:https://www.kaggle.com/saikrishna20/bird-tracking

python pandas geopandas
2个回答
0
投票
import kaggle.cli
import sys, requests
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import urllib
import plotly.express as px

# fmt: off
# download data set
url = "https://www.kaggle.com/saikrishna20/bird-tracking"
sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
kaggle.cli.main()
zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
dfs = {f.filename: pd.read_csv(zfile.open(f)) for f in zfile.infolist()}
# fmt: on

france_df = dfs["bird_tracking.csv"]
france_df = france_df.query("-3 < longitude < 4")
france_df = france_df.query("45 < latitude < 51")

px.scatter_mapbox(
    france_df,
    lat="latitude",
    lon="longitude",
    color="bird_name",
    color_discrete_map={"Eric": "turquoise", "Nico": "green", "Sanne": "brown"},
).update_layout(
    mapbox={
        "style": "carto-positron",
        "zoom": 5,
    },
    margin={"l": 0, "r": 0, "t": 0, "r": 0},
)


0
投票

您可以使用

cmap
参数来指定从 bird_palette 和数据框中唯一的鸟类名称创建的
colormap

bird_palette = {'Sanne': 'turquoise', 'Nico': 'green', 'Eric' : 'brown'}
cmap = matplotlib.colors.ListedColormap([bird_palette[b] for b in geo_df.bird_name.unique()])

map_france = geo_df.to_crs('EPSG:3857').plot(column='bird_name', linewidth=2, ax=ax, alpha=0.5, legend=True, markersize=10, cmap=cmap)

© www.soinside.com 2019 - 2024. All rights reserved.