Home > Software engineering >  matplotlib subplots: how to freeze x and y axis?
matplotlib subplots: how to freeze x and y axis?

Time:02-16

Good evening

matplotlib changes the scaling of the diagram when drawing with e.g. hist() or plot(), which is usually great.

Is it possible to freeze the x and y axes in a subplot after drawing, so that further drawing commands do not change them anymore? For example:

fig, (plt1, plt2) = plt.subplots(2, 1, figsize=(20, 10))
plt1.hist(…)
plt1.plot(…)

# How can this get done?:
plt1.Freeze X- and Y-Axis

# Those commands no longer changes the x- and y-axis
plt1.plot(…)
plt1.plot(…)

Thanks a lot, kind regards, Thomas

CodePudding user response:

Use plt.xlim and plt.ylim to get the current limits after plotting the initial plots, then use those values to set the limits after plotting the additional plots:

import matplotlib.pyplot as plt

# initial data
x = [1, 2, 3, 4, 5]
y = [2, 4, 8, 16, 32]
plt.plot(x, y)

# Save the current limits here
xlims = plt.xlim()
ylims = plt.ylim()

# additional data (will change the limits)
new_x = [-10, 100]
new_y = [2, 2]
plt.plot(new_x, new_y)

# Then set the old limits as the current limits here
plt.xlim(xlims)
plt.ylim(ylims)

plt.show()

Output figure (note how the x-axis limits are ~ [1, 5] even though the orange line is defined in the range [-10, 100]) : enter image description here

CodePudding user response:

To freeze x-axis specify the domain on the plot function:

import matplotlib.pyplot as plt

fig, (plt1, plt2) = plt.subplots(2, 1, figsize=(20, 10))

# range(min, max, step)
n = range(0, 10, 1)  # domain [min, max] = [0, 9]

# make sure your functions has equal length
f = [i * 2 for i in n]
g = [i ** 2 for i in n]

# keep x-axis scale the same by specifying x-axis on the plot function.
plt1.plot(n, f) # funtion (f) range depends on it's value [min, max]
plt1.plot(n, g) # funtion (g) range depends on it's value [min, max]

# range of (f) and (g) impacts the scaling of y-axis

See enter image description here

  • Related