Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Label patch in matplotlib

I am plotting rectangular patches in matplotlib in interactive mode. I want to add text to each patch. I do not want to annotate them as it decreases the speed. I am using 'label' property of patch but it is not working. Ayone know how to add 1 string to patch.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

plt.ion()
plt.show()

x = y = 0.1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
patch = ax1.add_patch(patches.Rectangle((x, y), 0.5, 0.5,
    alpha=0.1,facecolor='red',label='Label'))

plt.pause(0)
plt.close()
like image 439
TonyParker Avatar asked Sep 25 '15 15:09

TonyParker


1 Answers

You already know where the patch is, so you can calculate where the center is and add some text there:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

x=y=0.1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
patch= ax1.add_patch(patches.Rectangle((x, y), 0.5, 0.5,
    alpha=0.1,facecolor='red',label='Label'))

centerx = centery = x + 0.5/2 # obviously use a different formula for different shapes

plt.text(centerx, centery,'lalala')
plt.show()

centeredtext

The coordinates for plt.text determine where the text begins, so you can nudge it a bit in the x direction to get the text to be more centered e.g. centerx - 0.05. obviously @JoeKington's suggestion is the proper way of achieving this

like image 56
areuexperienced Avatar answered Oct 08 '22 15:10

areuexperienced