|
| 1 | +""" |
| 2 | +=================================== |
| 3 | +Default text rotation demonstration |
| 4 | +=================================== |
| 5 | +
|
| 6 | +The way Matplotlib does text layout by default is counter-intuitive to some, so |
| 7 | +this example is designed to make it a little clearer. |
| 8 | +
|
| 9 | +The text is aligned by its bounding box (the rectangular box that surrounds the |
| 10 | +ink rectangle). The order of operations is rotation then alignment. |
| 11 | +Basically, the text is centered at your x,y location, rotated around this |
| 12 | +point, and then aligned according to the bounding box of the rotated text. |
| 13 | +
|
| 14 | +So if you specify left, bottom alignment, the bottom left of the |
| 15 | +bounding box of the rotated text will be at the x,y coordinate of the |
| 16 | +text. |
| 17 | +
|
| 18 | +But a picture is worth a thousand words! |
| 19 | +""" |
| 20 | + |
| 21 | +import matplotlib.pyplot as plt |
| 22 | +import numpy as np |
| 23 | + |
| 24 | + |
| 25 | +def addtext(ax, props): |
| 26 | + ax.text(0.5, 0.5, 'text 0', props, rotation=0) |
| 27 | + ax.text(1.5, 0.5, 'text 45', props, rotation=45) |
| 28 | + ax.text(2.5, 0.5, 'text 135', props, rotation=135) |
| 29 | + ax.text(3.5, 0.5, 'text 225', props, rotation=225) |
| 30 | + ax.text(4.5, 0.5, 'text -45', props, rotation=-45) |
| 31 | + for x in range(0, 5): |
| 32 | + ax.scatter(x + 0.5, 0.5, color='r', alpha=0.5) |
| 33 | + ax.set_yticks([0, .5, 1]) |
| 34 | + ax.set_xlim(0, 5) |
| 35 | + ax.grid(True) |
| 36 | + |
| 37 | + |
| 38 | +# the text bounding box |
| 39 | +bbox = {'fc': '0.8', 'pad': 0} |
| 40 | + |
| 41 | +fig, axs = plt.subplots(2, 1) |
| 42 | + |
| 43 | +addtext(axs[0], {'ha': 'center', 'va': 'center', 'bbox': bbox}) |
| 44 | +axs[0].set_xticks(np.arange(0, 5.1, 0.5), []) |
| 45 | +axs[0].set_ylabel('center / center') |
| 46 | + |
| 47 | +addtext(axs[1], {'ha': 'left', 'va': 'bottom', 'bbox': bbox}) |
| 48 | +axs[1].set_xticks(np.arange(0, 5.1, 0.5)) |
| 49 | +axs[1].set_ylabel('left / bottom') |
| 50 | + |
| 51 | +plt.show() |
0 commit comments