|
| 1 | +# ---------------------------------------------------------------------------- |
| 2 | +# Title: Scientific Visualisation - Python & Matplotlib |
| 3 | +# Author: Nicolas P. Rougier |
| 4 | +# License: BSD |
| 5 | +# ---------------------------------------------------------------------------- |
| 6 | +import numpy as np |
| 7 | +import matplotlib.pyplot as plt |
| 8 | + |
| 9 | +dpi = 100 |
| 10 | +fig = plt.figure(figsize=(4.25, 1.5), dpi=dpi) |
| 11 | +ax = fig.add_axes([0,0,1,1], frameon=False, |
| 12 | + xlim=(0,4.25), ylim=(0,1.5), xticks=[], yticks=[]) |
| 13 | + |
| 14 | +fontsize = 48 |
| 15 | +renderer = fig.canvas.get_renderer() |
| 16 | +horizontalalignment = "left" |
| 17 | +verticalalignment = "center" |
| 18 | +position = (0.25, 1.5/2) |
| 19 | +color = "0.25" |
| 20 | + |
| 21 | +# Compute vertical and horizontal alignment offsets |
| 22 | +text = ax.text(0, 0, "Matplotlib", fontsize=fontsize) |
| 23 | +yoffset = {} |
| 24 | +for alignment in ["top", "center", "baseline", "bottom"]: |
| 25 | + text.set_verticalalignment(alignment) |
| 26 | + y = text.get_window_extent(renderer).y0/dpi |
| 27 | + yoffset[alignment] = y |
| 28 | + |
| 29 | +xoffset = {} |
| 30 | +for alignment in ["left", "center", "right"]: |
| 31 | + text.set_horizontalalignment(alignment) |
| 32 | + x = text.get_window_extent(renderer).x0/dpi |
| 33 | + xoffset[alignment] = x |
| 34 | + |
| 35 | +# Actual positioning of the text |
| 36 | +text.set_horizontalalignment(horizontalalignment) |
| 37 | +text.set_verticalalignment(verticalalignment) |
| 38 | +text.set_position(position) |
| 39 | + |
| 40 | + |
| 41 | +for name,y in yoffset.items(): |
| 42 | + y = position[1] - y + yoffset[verticalalignment] |
| 43 | + plt.plot([0.1, 3.75], [y, y], linewidth=0.5, color=color) |
| 44 | + plt.text(3.75, y, " "+name, color=color, |
| 45 | + ha="left", va="center", size="x-small") |
| 46 | + |
| 47 | +for name,x in xoffset.items(): |
| 48 | + x = position[0] - x + xoffset[horizontalalignment] |
| 49 | + plt.plot([x,x], [0.25, 1.25], linewidth=0.5, color=color) |
| 50 | + plt.text(x, 0.24, name, color = color, |
| 51 | + ha="center", va="top", size="x-small") |
| 52 | + |
| 53 | +P = [] |
| 54 | +for x in xoffset.values(): |
| 55 | + x = position[0] - x + xoffset[horizontalalignment] |
| 56 | + for y in yoffset.values(): |
| 57 | + y = position[1] - y + yoffset[verticalalignment] |
| 58 | + P.append((x,y)) |
| 59 | +P = np.array(P) |
| 60 | + |
| 61 | +ax.scatter(P[:,0], P[:,1], s=10, zorder=10, |
| 62 | + facecolor="white", edgecolor=color, linewidth=0.75) |
| 63 | + |
| 64 | +epsilon = 0.05 |
| 65 | +plt.text(P[3,0]+epsilon, P[3,1]-epsilon, "(0,0)", |
| 66 | + color=color, ha="left", va="top", size="x-small") |
| 67 | +plt.text(P[8,0]-epsilon, P[8,1]+epsilon, "(1,1)", |
| 68 | + color=color, ha="right", va="bottom", size="x-small") |
| 69 | + |
| 70 | +plt.savefig("text-alignments.pdf", dpi=600) |
| 71 | +plt.show() |
0 commit comments