Home > OS >  Matplotlib Wedge artists in legend
Matplotlib Wedge artists in legend

Time:07-13

I am generating a plot with a collection of wedges using matplotlib.patches.Wedge(). The wedges are different colors and with different angles subtended. I would like to include Wedge artists in a legend, but the following MWE is resulting in Line artists in the legend instead of Wedge artists.

enter image description here


update, you may run into some issues if you use Artist.update_from as it copies over a few too many properties. Instead you can manually specify which properties you want copied using this as an example:

import matplotlib.pylab as plt
from matplotlib.patches import Wedge
from matplotlib import rc

class WedgeHandler:
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        width, height = handlebox.width, handlebox.height
        r = min(width, height)
        
        handle = Wedge(
            center=(x0   width / 2, y0   height / 2),      # centers handle in handlebox
            r=r,                                           # ensures radius fits in handlebox
            width=r * (orig_handle.width / orig_handle.r), # preserves original radius/width ratio
            theta1=orig_handle.theta1,                     # copies the following parameters
            theta2=orig_handle.theta2,
            color=orig_handle.get_facecolor(),
            transform=handlebox.get_transform(),           # use handlebox coordinate system
        )
                        
        handlebox.add_artist(handle)
        return handle

plt.rcParams['axes.facecolor']='#EEEEEE'
plt.rcParams['savefig.facecolor']='#EEEEEE'

colors = ['#e41a1c','#377eb8','#4daf4a','#984ea3']
theta2 = [90, 180, 270, 360]
fig, ax = plt.subplots()

for i, (color, t2) in enumerate(zip(colors, theta2), start=1):
    wedge = Wedge((i, .5), 0.25, theta1=0, theta2=t2, width=0.25, color=color, label=f'category{i}')
    ax.add_artist(wedge)

ax.set_xlim(1-.25, i   .25)
    
legend = ax.legend(title='Default Handler', loc='upper left', bbox_to_anchor=(1.01, 1))
ax.add_artist(legend)

ax.legend(title='Custom Handler', loc='upper left', bbox_to_anchor=(1.01, 0.5), handler_map={Wedge: WedgeHandler()})
plt.show()

enter image description here

  • Related