pythonmatplotlibplot

Locking `matplotlib` x-axis range and then plotting on top of it


I can do the following in base R plotting.

x1 <- c(3, 4)
y1 <- c(5, 8)
x2 <- c(2, 5)
y2 <- c(5, 7)
plot(x1, y1, type = 'l')
lines(x2, y2, col = 'red')

in R

The key point is that, when I call that final lines command, the plotting function has already fixed the x-axis.

How can I do this in matplotlib to superimpose a new set of data on top of the current axis graph while keeping the x-axis range the same as before but allowing the y-axis range to accommodate the vertical range of the new points?

The code below fails because it expands the x-axis.

import matplotlib.pyplot as plt
x1 = [3, 4]
y1 = [5, 8]
x2 = [2, 5]
y2 = [4, 9]
fig, ax = plt.subplots()
ax.plot(x1, y1)
ax.plot(x2, y2)
plt.show()
plt.close()

python expands x-axis

The code below fails by cropping a bit too tight compared to how just a plot of x1 and y1 would be.

fig, ax = plt.subplots()
ax.plot(x1, y1)
ax.plot(x2, y2)
ax.set_xlim([min(x1), max(x1)])
plt.show()
plt.close()

python too tight

The code below has a little bit of padding to the right and to the left of the maximum and minmum values of x1 but does not superimpose the orange line for x2 and y2.

fig, ax = plt.subplots()
ax.plot(x1, y1)
# ax.plot(x2, y2)
# ax.set_xlim([min(x1), max(x1)])
plt.show()
plt.close()

python misses x2, y2

So how can I get matplotlib to superimpose the second set of data on top of the original graph while allowing the vertical axis to expand to include new y-values, yet keep the x-axis at the original range that contains a bit of padding to the right and the left?


Solution

  • Your second approach is quite close to what I think you want. You just need to store the original x-limits and then use those to reset the plot after it's resized:

    import matplotlib.pyplot as plt
    
    x1 = [3, 4]
    y1 = [5, 8]
    x2 = [2, 5]
    y2 = [4, 9]
    
    fig, ax = plt.subplots()
    ax.plot(x1, y1)
    xlim = ax.get_xlim()
    ax.plot(x2, y2)
    ax.set_xlim(xlim)
    plt.show()
    plt.close()
    

    enter image description here