How can I position a pie chart within another plot according to x, y coordinates?

42 views Asked by At

How would I go about positioning a pie chart to a specific location by x, y coordinates on a geopandas map plot using pandas and matplotlib?

I have tried first plotting individual points and then modifying the code but the same method does not appear to be transferable over.

-- Code for plotting points (ax is the axis of the subplot that the map plot is on) --

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

The same method does not work for plotting pie charts and any other solutions I tried, such as creating sub-axes, seem to break the plot entirely.

1

There are 1 answers

0
Serge de Gosson de Varennes On

You could do something like this. Mind that you would have to determine the positions of your pie charts yourslef

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()

Which gives something like this enter image description here