Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - Combine text/annotation coordinate systems

Tags:

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.

like image 592
stacker Avatar asked May 18 '20 23:05

stacker


People also ask

How do I annotate text in Matplotlib?

The annotate() function in pyplot module of matplotlib library is used to annotate the point xy with text s. Parameters: This method accept the following parameters that are described below: s: This parameter is the text of the annotation. xy: This parameter is the point (x, y) to annotate.

How do I annotate points in Matplotlib?

Annotating with Arrow. The annotate() function in the pyplot module (or annotate method of the Axes class) is used to draw an arrow connecting two points on the plot. This annotates a point at xy in the given coordinate ( xycoords ) with the text at xytext given in textcoords .


1 Answers

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

like image 151
C.K. Avatar answered Sep 30 '22 19:09

C.K.