Search code examples
pythonmatplotlibplotdata-visualizationaxis-labels

How do I plot with x-axis scaled down by a fixed quantity?


Say I have the following code:

import random
import matplotlib.pyplot as plt

lis = random.sample(range(1, 5000), 4000)

plt.plot(lis)

This plots the following:

enter image description here

The x-axis is printed from 0 to 4000 with a step size of 1. But I want it to be 0 to 4 with a step size of 0.0001.

I tried this:

import random
import numpy as np
import matplotlib.pyplot as plt

lis = random.sample(range(1, 5000), 4000)

plt.plot(lis)
plt.xlabel(np.linspace(0, 4, num=40001))

But this does not do the job:

enter image description here

How do I do this?


Solution

  • plt.plot() can take only one array as an argument (i.e. plt.plot(y)), then it interprets it as y values and plots it simply over the indices, as in your example. But if you want different x values, you can simply put them before the y values in the argument list like plt.plot(x, y), with x being your x value array, which obviuosly should have the same length as y.

    In your case this would mean

    import numpy as np
    import matplotlib.pyplot as plt
    
    lis = np.random.randint(0, 5000, 4000)
    x = np.arange(0, 4, 0.001)
    plt.plot(x, lis)
    

    See the docs for further reading: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html