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()
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()
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. obviously @JoeKington's suggestion is the proper way of achieving thiscenterx - 0.05
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With