Search code examples
pythonmatplotlibscaleaxis

Python Pyplot: How to scale x-axis independant from number of list-elements?


Just want to plot a list with 50 (actually 51) elements: The list indices from 0 to 50 should represent meters from 0 to 10 meters on the x-axis, while the index of every further element increases by 0.2 meters. Example:

list = [2.5, 3, 1.5, ... , 7, 9]
len(list)
>>50

I would like the x-axis plotted from 0 to 10 meters, i.e. (x,y)==(0, 2.5), (0.2, 3), (0.4, 1.5), ..., (9.8, 7), (10, 9)

Instead, the list is obviously plotted on an x-scale from 0 to 50. Any idea how to solve the problem? Thanks!


Solution

  • I would avoid naming a list object list. It confuses the namespace. But try something like

    import numpy as np
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    x = np.arange(0, 10, 0.2)
    y = [2.5, 3, 1.5, ... , 7, 9]
    ax.plot(x, y)
    plt.show()
    

    It creates a list of point on the x-axis, which occur at multiples of 0.2 using np.arange, at which matplotlib will plot the y values. Numpy is a library for easily creating and manipulating vectors, matrices, and arrays, especially when they are very large.

    Edit:

    fig.add_subplot(N_row,N_col,plot_number) is the object oriented approach to plotting with matplotlib. It's useful if you want to add multiple subplots to the same figure. For example,

    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)
    

    adds two subplots to the same figure fig. They will be arranged one above the other in two rows. ax2 is the bottom subplot. Check out this relevant post for more info.

    To change the actual x ticks and tick labels, use something like

    ax.set_xticks(np.arange(0, 10, 0.5))
    ax.set_xticklabels(np.arange(0, 10, 0.5)) 
    # This second line is kind of redundant but it's useful if you want 
    # to format the ticks different than just plain floats.