jmquintana79
5/20/2016 - 12:06 AM

Customized legend text box

Customized legend box in Matplotlib

import matplotlib.pyplot as plt
import numpy as np

# data
x = np.arange(10)

# create figure
fig = plt.figure()
ax = plt.subplot(111)

# plot
for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

# shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
                 box.width, box.height * 0.9])

# put a legend below current axis
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=5)
          
# include text box
xpos = 0.05; ypos = 0.95
textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma)
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
ax.text(xpos,ypos, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=props)

ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})

ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)

ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik')

ax.text(0.95, 0.01, 'colored text in axes coords',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)

# text and arrow to point
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))
            
            

        
# display
plt.show()