stacker
stacker

Reputation: 118

Matplotlib - Combine text/annotation coordinate systems

Is it possible to combine two different coordinate systems when locating text/annotations on a plot? As described in this question you can specify an annotation's location as a fractal position of the plot's size. This is also covered further here in the documentation.

However I want to specify the x-coord of an annotation in the fractal coord system and the y-coord in the data coord system. This will allow me to attach an annotation to a horizontal line, but ensure that the annotation is always near (some fraction of the plot size away from) the edge of the plot.

Upvotes: 6

Views: 1036

Answers (1)

C.K.
C.K.

Reputation: 1571

Use blended_transform_factory(x_transform,y_transform). The function return a new transformation which applys x_transform for x-axis and y_transform for y-axis. For example:

import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
import numpy as np

x = np.linspace(0, 100,1000)
y = 100*np.sin(x)
text = 'Annotation'

f, ax = plt.subplots()
ax.plot(x,y)
trans = blended_transform_factory(x_transform=ax.transAxes, y_transform=ax.transData)
ax.annotate(text, xy=[0.5, 50], xycoords=trans,ha='center')

Then you put the annotation at the center of x-axis, and the y=50 position of y-axis.

enter image description here

Upvotes: 5

Related Questions