Matplotlib: Where is the first axes object located?

Usually when I make a single plot, I just call fig,ax = plt.subplots() without specification as to where to place the axes object in the figure. But when I want to place a legend or as in the example below, a checkbox, then the relative coordinates are with respect to the figure. So often my box is just all over the place.

In this case I would like to place the box right next to the graph I already have in ax1, but I don’t know where ax1 is positioned.

import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

x = range(0,10)
y = range(0,10)

fig, ax1 = plt.subplots()
ax1.plot(x,y, color = "blue")
ax1.set_title('This is my graph')

#create the check box [left/bottom/width/height]
ax2 = plt.axes([0.95, 0.975, 0.05, 0.025])
check_box = CheckButtons(ax2, ['On',], [False,])

plt.show()

Does matplotlib place the first ax1 object in a constant position such that one can be sure where to place a legend or a box relative to it?
Or does one have to address this problem differently?

Thanks for your help!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I would create the two axes at the same time, as in the following. Note: gridspec_kw={'width_ratios': [4, 1]} allows you to specify how much larger is the first axes with respect to the second.

import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

x = range(0,10)
y = range(0,10)

fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [4, 1]})
ax1.plot(x,y, color = "blue")
ax1.set_title('This is my graph')

#create the check box [left/bottom/width/height]
ax2.axis(False)
ax2.set_aspect("equal")
check_box = CheckButtons(ax2, ['On',], [False,])

plt.tight_layout()
plt.show()


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x