我可以根据访问某些特定国家的次数进行颜色渐变或颜色变化吗?

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

我一直在尝试使用 geopandas 和 folium 以及其他常见的 python 库。我给自己设定了一个小挑战,制作了一张地图,并用单一颜色突出显示了我去过的国家。不过,我想在其中添加更多的功能,如果我去过不止一次的话,我想呈现一个不同的国家颜色。例如,台湾,我去过一次,所以是橙色,日本,两次,所以是红色,韩国,3次,所以是紫色等等...... 我最近参考了 matplotlib,但代码无法正常工作,可以给我一些建议吗?

这是我的代码 excel 文件有 2 列,A 列称为“国家”,由中国、日本、德国等国家/地区的名称组成,B 列称为“访问”,由我前往相应国家/地区的次数组成。

from google.colab import files
import pandas as pd
import geopandas as gpd
import folium
import matplotlib.cm as cm
import matplotlib.colors as colors

# Uploads file
uploaded = files.upload()


filename = next(iter(uploaded))

# Read  Excel file to a pandas DataFrame
df = pd.read_excel(filename)

# world geometry 
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# Merge data with the world data
visited = world.merge(df, left_on='name', right_on='Country')

# map createw
m = folium.Map(location=[0, 0], zoom_start=2)

# boundaries 
for _, r in world.iterrows():
    sim_geo = gpd.GeoSeries(r['geometry']).simplify(tolerance=0.001)
    geo_j = folium.GeoJson(data=sim_geo.to_json(), style_function=lambda x: {'color': 'black'})
    folium.Popup(r['name']).add_to(geo_j)
    geo_j.add_to(m)

# Function to set the color based on the number of visits
def color(visits):
    # Create a colormap for 4+ visits
    colormap = cm.get_cmap('YlOrRd')

    # Normalize the visits to 0-1
    norm = colors.Normalize(vmin=1, vmax=4)

    # Get the color from the colormap and convert to hex
    rgba = colormap(norm(visits), bytes=True)
    return '#{:02x}{:02x}{:02x}'.format(rgba[0], rgba[1], rgba[2])

for _, r in visited.iterrows():
    sim_geo = gpd.GeoSeries(r['geometry']).simplify(tolerance=0.001)
    geo_j = folium.GeoJson(data=sim_geo.to_json(), style_function=lambda x: {'fillColor':                     color(r['Visits'])})
    folium.Popup(r['name']).add_to(geo_j)
    geo_j.add_to(m)

#  map
m
python matplotlib colors geopandas folium
1个回答
0
投票

看起来你可以用更简单的方式制作这样的地图,只需使用 GeoPandas 绘图工具,即不使用 folium。假设您有这些数据:

国家 参观
中国 1
伊朗 3
日本 2
朝鲜 3
南非 2
委内瑞拉 4

如果将其存储在 CSV 文件中,您可以像这样提取并显示它:

import pandas as pd
import geopandas
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors


# read a CSV file to a pandas DataFrame
df = pd.read_csv('visited_countries.csv', delimiter='\t')

visited = list(df['Country'])  # countries visited
num = list(df['Visits'])  # number of visits

# get the countries dataset from Natural Earth
file_with_all_countries = geopandas.datasets.get_path('naturalearth_lowres')
all_gdf = geopandas.read_file(file_with_all_countries)
# set the names of the countries as the index
all_gdf = all_gdf.set_index("name")
# get the data for the visited countries
visited_gdf = all_gdf.loc[visited]
# create a column for the number of visits
visited_gdf["num"] = num
cmap = cm.YlOrRd
# show all the countries with the minimum color from the cmap, indicating 0 visits by default 
ax = all_gdf.plot(facecolor=cmap(0), edgecolor='grey')
# paint the visited countries
norm = colors.BoundaryNorm(sorted(set(num)), ncolors=cmap.N, extend='both')
visited_gdf.plot(ax=ax, column='num', legend=True, vmin=min(num), vmax=max(num), cmap=cmap, norm=norm)
plt.title('Country Visits')
plt.show()

结果如下:

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