Gundheri
Gundheri

Reputation: 95

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!

Upvotes: 0

Views: 50

Answers (1)

Davide_sd
Davide_sd

Reputation: 13185

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()

Upvotes: 1

Related Questions