user6936420
user6936420

Reputation:

Annotation box does not appear in matplotlib

The planned annotation box does not appear on my plot, however, I've tried a wide range of values for its coordinates.

What's wrong with that?!

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def f(s,t):
    a = 0.7
    b = 0.8
    Iext= 0.5
    tau = 12.5
    v = s[0]
    w = s[1]
    dndt = v - np.power(v,3)/3 - w + Iext
    dwdt = (v + a - b * w)/tau
    return [dndt, dwdt]

t = np.linspace(0,200)
s0=[1,1]

s = odeint(f,s0,t)

plt.plot(t,s[:,0],'b-', linewidth=1.0)
plt.xlabel(r"$t(sec.)$")
plt.ylabel(r"$V (volt)$")
plt.legend([r"$V$"])

annotation_string = r"$I_{ext}=0.5$" 
plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

plt.show()

Upvotes: 1

Views: 4095

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339795

The coordinates to plt.text are data coordinates by default. This means in order to be present in the plot they should not exceed the data limits of your plot (here, ~0..200 in x direction, ~-2..2 in y direction).

Something like plt.text(10,1.8) should work.

The problem with that is that once the data limits change (because you plot something different or add another plot) the text item will be at a different position inside the canvas.

If this is undesired, you can specify the text in axes coordinates (ranging from 0 to 1 in both directions). In order to place the text always in the top left corner of the axes, independent on what you plot there, you can use e.g.

plt.text(0.03,0.97, annotation_string, bbox=dict(facecolor='red', alpha=0.5), 
         transform=plt.gca().transAxes, va = "top", ha="left")

Here the transform keyword tells the text to use Axes coordinates, and va = "top", ha="left" means, that the top left corner of the text should be the anchor point.

Upvotes: 4

Beatdown
Beatdown

Reputation: 229

The annotation is appearing far above your plot because you have given a 'y' coordinate of 60, whereas your plot ends at '2' (upwards).

Change the second argument here:

plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

It needs to be <=2 to show up on the plot itself. You may also want to change the x coorinate (from 15 to something less), so that it doesn't obscure your lines.

e.g.

plt.text(5, 1.5, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

Don't be alarmed by my (5,1.5) suggestion, I would then add the following line to the top of your script (beneath your imports):

rcParams['legend.loc'] = 'best'

This will choose a 'best fit' for your legend; in this case, top left (just above your annotation). Both look quite neat then, your choice though :)

Upvotes: 1

Related Questions