如何根据x, y坐标在另一图中定位饼图?

0 投票
1 回答
40 浏览
提问于 2025-04-12 05:31

我想知道如何在使用pandas和matplotlib绘制的geopandas地图上,将饼图放到特定的x、y坐标位置。

我先是尝试先绘制单独的点,然后修改代码,但发现这种方法不能直接用在饼图上。

-- 绘制点的代码(ax是地图绘图所在的子图的坐标轴) --

ax.plot(x, y, color=color, markersize=size, marker="o")

但是同样的方法在绘制饼图时不管用,我尝试的其他解决方案,比如创建子坐标轴,似乎完全破坏了图表。

相关问题:

1 个回答

0

你可以这样做。需要注意的是,你得自己确定饼图的位置。

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

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
gdf = gdf[gdf.name == "United States of America"]


df_pie_data = pd.DataFrame({
    'x': [-100, -90],
    'y': [40, 45],
    'category_a': [10, 20],
    'category_b': [30, 15]
})

def add_pie_chart(ax, data_row, sizes, coords):
    bbox = ax.get_position()  
    trans = ax.transData + fig.transFigure.inverted()  
    x_fig, y_fig = trans.transform(coords)  
    width, height = 0.1, 0.1  
    pie_ax = fig.add_axes([x_fig - 2*width , y_fig - 2*height, width, height], aspect='equal')
    pie_ax.pie(sizes, startangle=90) 

fig, ax = plt.subplots(1, 1, figsize=(10, 10))
gdf.plot(ax=ax)

for idx, row in df_pie_data.iterrows():
    x, y = row['x'], row['y']
    sizes = [row['category_a'], row['category_b']]  
    add_pie_chart(ax, row, sizes, (x, y))

plt.show()

这样就能得到类似这样的效果:

这里输入图片描述

撰写回答