matplotlib geopandas 绘制叶绿素,并为颜色方案设置容器

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

如何为同一个图中的三个
axes
设置一致的配色方案?

以下应该是一个完全可重现的示例,用于运行代码并获得与我在下面发布的相同的数字。

国家统计局获取 shapefile 数据。在终端中将其作为

bash
文件/命令运行。

wget --output-document 'LA_authorities_boundaries.zip' 'https://opendata.arcgis.com/datasets/8edafbe3276d4b56aec60991cbddda50_1.zip?outSR=%7B%22latestWkid%22%3A27700%2C%22wkid%22%3A27700%7D&session=850489311.1553456889'

mkdir LA_authorities_boundaries
cd LA_authorities_boundaries
unzip ../LA_authorities_boundaries.zip

读取 shapefile 并创建一个虚拟

GeoDataFrame
用于重现行为的 Python 代码。

import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt

gdf = gpd.read_file(
    'LA_authorities_boundaries/Local_Authority_Districts_December_2015_Full_Extent_Boundaries_in_Great_Britain.shp'
)

# 380 values
df = pd.DataFrame([])
df['AREA_CODE'] = gdf.lad15cd.values
df['central_pop'] = np.random.normal(30, 15, size=(len(gdf.lad15cd.values)))
df['low_pop'] = np.random.normal(10, 15, size=(len(gdf.lad15cd.values)))
df['high_pop'] = np.random.normal(50, 15, size=(len(gdf.lad15cd.values)))

加入来自 ONS 的 shapefile 并创建一个

geopandas.GeoDataFrame

def join_df_to_shp(pd_df, gpd_gdf):
    """"""
    df_ = pd.merge(pd_df, gpd_gdf[['lad15cd','geometry']], left_on='AREA_CODE', right_on='lad15cd', how='left')

    # DROP the NI counties
    df_ = df_.dropna(subset=['geometry'])

    # convert back to a geopandas object (for ease of plotting etc.)
    crs = {'init': 'epsg:4326'}
    gdf_ = gpd.GeoDataFrame(df_, crs=crs, geometry='geometry')
    # remove the extra area_code column joined from gdf
    gdf_.drop('lad15cd',axis=1, inplace=True)

    return gdf_

pop_gdf = join_df_to_shp(df, gdf)

绘制图

fig,(ax1,ax2,ax3,) = plt.subplots(1,3,figsize=(15,6))

pop_gdf.plot(
    column='low_pop', ax=ax1, legend=True,  scheme='quantiles', cmap='OrRd',
)
pop_gdf.plot(
    column='central_pop', ax=ax2, legend=True, scheme='quantiles', cmap='OrRd',
)
pop_gdf.plot(
    column='high_pop', ax=ax3, legend=True,  scheme='quantiles', cmap='OrRd',
)
for ax in (ax1,ax2,ax3,):
    ax.axis('off')

enter image description here

我希望所有三个
ax
对象共享相同的容器(最好是
central_pop
场景
quantiles
),以便整个图形的图例保持一致。一个场景(中央)的
quantiles
将成为所有场景的
levels

这样我应该在最右侧看到较深的颜色(更红)

ax
,显示
high_pop
场景。

如何为整个图形/每个

ax
对象设置颜色方案箱?

我能看到这个工作的最简单的方法是 a) 为

geopandas.plot()
函数提供一组 bin b) 从一个
ax
中提取颜色方案/箱并将其应用到另一个。

python python-3.x matplotlib geopandas
2个回答
16
投票

从 geopandas 0.5 开始,您可以使用定义为

scheme="User_Defined"
的自定义方案,并通过
classification_kwds
提供分箱。

import geopandas as gpd
print(gpd.__version__)   ## 0.5
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt 

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) 
gdf['quant']=np.random.rand(len(gdf))*100-20

fig, ax = plt.subplots()

gdf.plot(column='quant', cmap='RdBu', scheme="User_Defined", 
         legend=True, classification_kwds=dict(bins=[-10,20,30,50,70]),
         ax=ax)

plt.show()

enter image description here

因此剩下的任务是从其中一列的分位数中获取 bin 列表。这应该很容易完成,例如通过

import mapclassify
bins = mapclassify.Quantiles(gdf['quant'], k=5).bins

然后在上面的代码中设置

classification_kwds=dict(bins=bins)

enter image description here


0
投票

您也可以尝试下面的解决方案(注意Cluster_As_Text是字符串类型):

import matplotlib.pyplot as plt
import geopandas as gpd
import matplotlib.colors as colors

# Define color dictionary for clusters
color_dict = {'0': 'green', '1': 'yellow', '2': 'red'}  
# Add more colours as needed

# Create a figure and axis
fig, ax = plt.subplots(figsize=(15, 10))

# Plot GeoDataFrame, coloring by 'Cluster_As_Text' column
merged.plot(ax=ax, column="Cluster_As_Text", legend=True, 
cmap=colors.ListedColormap(list(color_dict.values())))

# Customize legend position and appearance
legend = ax.get_legend()
legend.set_title('Cluster')
legend.set_bbox_to_anchor((0.25, 0.96))  # Adjust position of legend

# Show plot
plt.show()

获得如下输出:

enter image description here

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