Issue
I am trying to add an image below the x axis label in a matplotlib plot, but as I move the image position further down, it will eventually go outside the plot area. Here is a minimum example:
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)
im = plt.imread('plane.jpg')
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_xlabel("my label")
imagebox = OffsetImage(im, zoom = 0.05)
ab = AnnotationBbox(imagebox, (1, 0), xycoords='axes fraction', box_alignment=(1.1, 1), frameon = False)
ax.add_artist(ab)
fig.savefig("example.png")
plt.show()
Where the image can be found here and the result here.
I could not find online any example that does that. I would like the plot area to be automatically extended below the x axis in order to accommodate the image. Is it possible in matplotlib?
Thanks a lot,
Solution
Turning my comment above into an answer: setting bbox_inches="tight"
in the call to savefig
will change the size of the saved figure to fit the artists it contains. I have tested this with Matplotlib versions between v3.6 and v3.8.
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)
im = plt.imread('plane.jpg')
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_xlabel("my label")
imagebox = OffsetImage(im, zoom = 0.05)
ab = AnnotationBbox(imagebox, (1, 0), xycoords='axes fraction', box_alignment=(1.1, 1), frameon = False)
ax.add_artist(ab)
fig.savefig("example.png", bbox_inches="tight")
Answered By - RuthC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.