Im facing a strange behaviour from matplotlib when equal aspect ratio is preserved.
For starters, this is the minimum code sample to show this behaviour. First with the correct behaviour and second with the crooked behaviour
import matplotlib.pyplot as plt
import numpy as np
# Generate some random data
x = np.arange(0, 10, 0.1)
y = np.random.randn(len(x))
# Create a plot
fig, ax = plt.subplots()
# ax.set_aspect('equal', 'datalim')
# Set x-axis limits
ax.set_xlim(2, 5)
# Print the x and y limits
print(f"x-axis limits before plotting: {ax.get_xlim()}")
print(f"y-axis limits before plotting: {ax.get_ylim()}")
ax.plot(x, y*10)
# Print the x and y limits
print(f"x-axis limits after plotting: {ax.get_xlim()}")
print(f"y-axis limits after plotting: {ax.get_ylim()}")
# Set x-axis limits
ax.set_xlim(2, 5)
# Print the x and y limits
print(f"x-axis limits after setting xlim: {ax.get_xlim()}")
print(f"y-axis limits after setting xlim: {ax.get_ylim()}")
# Show the plot
plt.show()
So this prints
x-axis limits before plotting: (2.0, 5.0)
y-axis limits before plotting: (0.0, 1.0)
x-axis limits after plotting: (2.0, 5.0)
y-axis limits after plotting: (-23.30742047433786, 21.093948480431905)
x-axis limits after setting xlim: (2.0, 5.0)
y-axis limits after setting xlim: (-23.30742047433786, 21.093948480431905)
which correctly correspond to the plot being generated
Now the strange thing happens when I uncomment the ax.set_aspect(‘equal’, ‘datalim’) line.
It prints below data
x-axis limits before plotting: (2.0, 5.0)
y-axis limits before plotting: (0.0, 1.0)
x-axis limits after plotting: (2.0, 5.0)
y-axis limits after plotting: (-31.012258207723225, 22.633044899779353)
x-axis limits after setting xlim: (2.0, 5.0)
y-axis limits after setting xlim: (-31.012258207723225, 22.633044899779353)
But shows a graph with completely different limits
My questions are:
- is there anyway to get matplotlib to return the correct x,y limits
- is there anyway to keep AR by changing only y data limits keeping manually set xlimits untouched ?