pythonmatplotlib

Position an axis at a point location


I have a plot with a line graph. I need to place a new axis at a point/coordinate and plot a pie chart on the new axis so the pie is centered on the point.

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 3))
ax.set_xlim(0,16)
ax.set_ylim(8,12)

#Plot a sine wave
x = np.arange(0, 5*np.pi, 0.1)
y = np.sin(x)+10
ax.plot(x, y, color="blue")

#Plot a red point at x=12, y=10
ax.plot(12,10,marker="o", color="red")

#Add a new axes to the plot

#Normalize the points coordinates to range between 0 and 1
x_norm = (12-0)/(16-0) #0.75
y_norm = (10-8)/(12-8) #0.5

#Add an ax at the normalized coordinates
left=0.75
bottom=0.5
width=0.1
height=0.1
sub_ax = fig.add_axes(rect=(left, bottom, width, height))

enter image description here

sub_ax.pie((0.2,0.3,0.5))

The pie is centered on the new axis center. I cant figure out the logic to get it centered at the point?

enter image description here


Solution

  • You could use the inset_axes method, (based on the last option from this answer) e.g.,

    import matplotlib.pyplot as plt
    import numpy as np
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 3))
    ax.set_xlim(0,16)
    ax.set_ylim(8,12)
    
    #Plot a sine wave
    x = np.arange(0, 5*np.pi, 0.1)
    y = np.sin(x)+10
    ax.plot(x, y, color="blue")
    
    #Plot a red point at x=12, y=10
    point = (12, 10)
    ax.plot(*point, marker="o", color="red")
    
    # width and height in data coordinates
    width = 2
    height = 0.5
    
    # subtract half the width/height from the left/bottom positions
    position = [point[0] - width / 2, point[1] - height / 2, width, height]
    
    sub_ax = ax.inset_axes(position, transform=ax.transData)
    sub_ax.pie((0.2,0.3,0.5))
    

    plot with inset axes with pie chart