pythonmatplotlib

In a matplotlib plot is there a way to automatically set the xlim after it has been set then set to None?


I am working on a GUI where a user can specify the both the min and max x limit. When the value is left blank I would like it to be automatically calculated. One limit can be set while the other is automatically calculated by setting it to None. But after setting one limit and then setting it to None does not automatically update the limit. Both values can be automatically calculated by using set_xlim(auto=True) but this forces both values to be automatically calculated and does not allow only one value to be automatically calculated. Is there a way of having just one limit automatically re-calculated? For example in MATLAB xlim[-Inf, 4] would automatically calculate the first limit.

Below is an example without a GUI

import matplotlib.pyplot as plt

x_data = [1, 2, 3, 4, 5]
y_data = [1, 2, 3, 4, 5]

fig, ax = plt.subplots(1)

ax.plot(x_data, y_data, '.')

# Initially limits are automatically calculated
ax.set_xlim(auto=True)
print(ax.get_xlim()) # prints: (np.float64(0.8), np.float64(5.2))

# User sets value with GUI
ax.set_xlim(2, 4)
print(ax.get_xlim()) # prints: (np.float64(2.0), np.float64(4.0))

# Later user changes their mind and leaves the first limit blank
ax.set_xlim(None, 4) # 
print(ax.get_xlim()) # prints: (np.float64(2.0), np.float64(4.0))

plt.show()

Solution

  • As noted in the comment, we can "reset" to automatic axis limits using ax.set_xlim(auto=True) again followed by ax.autoscale_view().

    # Later user changes their mind and leaves the first limit blank
    ax.set_xlim(auto=True)
    ax.autoscale_view()
    ax.set_xlim(None, 4)
    print(ax.get_xlim()) # prints: (0.8, 4.0)