pythonmatplotlibplot-annotationstext-rotation

How to avoid text being upside down after rotation


I am trying to place labels on an image with Matplotlib. I need to place labels in eight octilinear directions around a node, for which I am currently using the text function with rotation mode anchor.

However, with some angles, e.g. 180°, the label is left of the node as I want it to be, but the text is upside down as a result of the rotation. My workaround so far is to flip the text again using the upsidedown library:

ax.text(x + x_fac * SCALE / 10.0, y + y_fac * SCALE / 10.0, upsidedown.transform(stop_label),
        rotation=angle, rotation_mode='anchor')

However, some characters are not displayed correctly when flipped. This is why I am searching for a better way to do this. Does someone have an idea?


Solution

  • Check out horizontalalignment. preview image

    ax.text(0.5, 0.5, "Right", horizontalalignment="right", rotation=45, rotation_mode="anchor")
    ax.text(0.5, 0.5, "Left", horizontalalignment="left", rotation=315, rotation_mode="anchor")
    

    When right-aligned, text will be left of the node, so 180° become 0°. There is no need for upsidedown.