Search code examples
pythonpandasmatplotlibyaxisx-axis

Fixing x axis scale and autoscale y axis


I would like to plot only part of the array, fixing the x part, but letting the y part autoscale. I tried as shown below, but it does not work.

Any suggestions?

import numpy as np
import matplotlib.pyplot as plt

data=[np.arange(0,101,1),300-0.1*np.arange(0,101,1)]

plt.figure()

plt.scatter(data[0], data[1])
plt.xlim([50,100])
plt.autoscale(enable=True, axis='y')

plt.show()

enter image description here


Solution

  • Autoscaling always uses the full range of the data, so the y-axis is scaled by full extent of the y-data, not just what's within the x-limits.

    If you'd like to display a subset of the data, then it's probably easiest to plot only that subset:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x, y = np.arange(0,101,1) ,300 - 0.1*np.arange(0,101,1)
    mask = (x >= 50) & (x <= 100)
    
    fig, ax = plt.subplots()
    ax.scatter(x[mask], y[mask])
    
    plt.show()
    

    enter image description here