Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text inside a filled area in matplotlib

I have a graph in which I have filled out a certain area. I'm looking to add an annotation/label to the filled area but can't figure out how. Please find my code below:

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2 * np.pi, 100)
Ya = np.sin(X)
plt.plot(X, Ya)
plt.fill_between(X, Ya, 0,
                 where = (X >=3.00) & (Ya<= 0),
                 color = 'b',alpha=.1)

graph example

I'd like to add an annotation to the part filled blue. Any help would be greatly appreciated!

like image 952
Fiach ONeill Avatar asked Oct 16 '25 03:10

Fiach ONeill


1 Answers

You can grab the output of the fill_between, get its bounding box and use its center to position the text:


import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
X = np.linspace(0, 2 * np.pi, 100)
Ya = np.sin(X)
ax.plot(X, Ya)
filled_poly = ax.fill_between(X, Ya, 0,
                              where=(X >= 3.00) & (Ya <= 0),
                              color='b', alpha=.1)
(x0, y0), (x1, y1) = filled_poly.get_paths()[0].get_extents().get_points()

ax.text((x0 + x1) / 2, (y0 + y1) / 2, "Filled\npolygon", ha='center', va='center', fontsize=16, color='crimson')
plt.show()

using the center of the bounding box to position text

like image 127
JohanC Avatar answered Oct 18 '25 17:10

JohanC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!