NumPy’s linspace Function in Python

When I was working on a data visualization project, I needed to generate a sequence of evenly spaced points for plotting a complex function. The issue is, manually creating these sequences can be tedious and error-prone. That’s when NumPy’s linspace function came to my rescue.

In this article, I’ll cover everything you need to know about NumPy’s linspace function – from basic usage to advanced applications.

So let’s get in!

NumPy Linspace

NumPy’s linspace is one of the most useful functions for creating evenly spaced number sequences. Unlike range() or arange(), linspace lets you specify the number of points you want, making it perfect for plotting and scientific computing.

Read Python NumPy Not Found: Fix Import Error

Basic Usage of NumPy Linspace in Python

Now, I will explain to you some basic usage of NumPy Linspace in Python

1 – Create a Simple Evenly Spaced Array

To use linspace, you first need to have Python NumPy installed. If you don’t have it yet, you can install it using pip:

import numpy as np

# Create an array with 5 elements from 0 to 10
result = np.linspace(0, 10, 5)
print(result)

Output:

[ 0.   2.5  5.   7.5 10. ]

I executed the above example code and added the screenshot below.

np linspace

In this example, linspace generates 5 evenly spaced numbers starting from 0 and ending at 10. The function automatically calculates the step size (2.5 in this case).

Check out Create a Matrix in Python

2 – Exclude the Endpoint

Sometimes you don’t want to include the endpoint in your Python array. For this case, linspace has the endpoint parameter:

# Create an array without including the endpoint
result = np.linspace(0, 10, 5, endpoint=False)
print(result) 

Output:

[0. 2. 4. 6. 8.]

I executed the above example code and added the screenshot below.

np.linspace

When you set endpoint=False, linspace generates points from start to end but excludes the end value.

Read Random Number Between Two Values in Numpy

3 – Get the Step Size

What if you need to know the size of each step? Linspace can return that too:

# Get both the array and the step size
result, step = np.linspace(0, 10, 5, retstep=True)
print(f"Array: {result}")
print(f"Step size: {step}")

Output:

Array: [ 0.   2.5  5.   7.5 10. ]
Step size: 2.5

I executed the above example code and added the screenshot below.

numpy linspace

By setting retstep=True, linspace returns both the array and the step size between points.

Real-World Applications of NumPy Linspace

Let me explain some real-world applications of NumPy Linspace in Python

Check out Create a Python Empty Matrix

1. Create Sine Waves for Audio Processing

One practical application of linspace is generating sine waves for audio processing:

import numpy as np
import matplotlib.pyplot as plt

# Create a time array for a 1-second audio sample at 44.1kHz
sample_rate = 44100
duration = 1.0
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)

# Generate a 440Hz sine wave (A4 note)
frequency = 440
audio_signal = np.sin(2 * np.pi * frequency * t)

# Plot the first 100 samples
plt.figure(figsize=(10, 4))
plt.plot(t[:100], audio_signal[:100])
plt.title('440Hz Sine Wave (A4 note)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.show()

In this example, I used linspace to create a time array for digital audio at CD quality (44.1 kHz).

2. Plot Temperature Data for Major US Cities

Another common use is for data visualization of real-world data:

import numpy as np
import matplotlib.pyplot as plt

# Average monthly temperatures for New York (°F)
months = np.linspace(1, 12, 12)
nyc_temps = [33, 35, 43, 54, 65, 74, 79, 77, 70, 58, 48, 38]

# Average monthly temperatures for Los Angeles (°F)
la_temps = [59, 60, 62, 64, 68, 72, 76, 77, 76, 71, 65, 59]

plt.figure(figsize=(10, 6))
plt.plot(months, nyc_temps, 'b-o', label='New York')
plt.plot(months, la_temps, 'r-o', label='Los Angeles')
plt.xticks(months, ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                   'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
plt.ylabel('Temperature (°F)')
plt.title('Average Monthly Temperatures in Major US Cities')
plt.grid(True)
plt.legend()
plt.show()

In this example, I used linspace to create the month indices for plotting temperature data.

3. Create Custom Colormaps

Linspace is also perfect for creating custom colormaps for data visualization:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# Create a custom gradient from blue to red
n_bins = 100
color_array = np.zeros((n_bins, 4))
color_array[:, 0] = np.linspace(0, 1, n_bins)  # Red increases
color_array[:, 2] = np.linspace(1, 0, n_bins)  # Blue decreases
color_array[:, 3] = 1  # Alpha stays at 1

# Create the custom colormap
custom_cmap = LinearSegmentedColormap.from_list("BlueToRed", color_array)

# Create some sample data
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)

# Plot with the custom colormap
plt.figure(figsize=(8, 6))
plt.pcolormesh(X, Y, Z, cmap=custom_cmap)
plt.colorbar()
plt.title('Custom Blue-Red Colormap')
plt.show()

Here, I used linspace to create smooth color transitions for a custom colormap.

Advanced Features of NumPy Linspace

Let me show you some advanced features of NumPy linspace in Python

Read NumPy Reset Index of an Array in Python

1. Work with Complex Numbers

Linspace can also generate arrays of complex numbers:

# Create a sequence of complex numbers
complex_array = np.linspace(1j, 10+5j, 5)
print(complex_array)
# Output: [0.+1.j 2.5+2.j 5.+3.j 7.5+4.j 10.+5.j]

This is particularly useful in signal processing and electrical engineering applications.

2. Use Linspace with DataTypes

You can specify the data type for your array:

# Create an array with a specific data type
int_array = np.linspace(0, 10, 5, dtype=np.int32)
print(int_array)
# Output: [ 0  2  5  7 10]

This becomes important when working with large datasets where memory usage is a concern.

3. Create Logarithmic Space

While not linspace directly, NumPy also offers logspace, which creates points evenly spaced on a log scale:

# Create a logarithmic space
log_array = np.logspace(1, 3, 4)
print(log_array)
# Output: [  10.   100.  1000. 10000.]

This is equivalent to 10**np.linspace(1, 3, 4) and is extremely useful for creating scales that span multiple orders of magnitude.

Read np.genfromtxt() Function in Python

Performance Considerations

One thing to keep in mind is that linspace pre-allocates the entire array in memory. For very large arrays, this might cause memory issues. In such cases, you might want to consider alternatives:

# For very large sequences, you might prefer:
large_range = range(0, 1000000)  # doesn't create the whole sequence in memory
large_array = np.arange(0, 1000000)  # more memory-efficient than linspace for integer steps

However, for most scientific and data visualization needs, linspace remains the most convenient option due to its precision in dividing intervals.

I hope you found this article helpful in understanding NumPy’s linspace function. It’s a simple yet powerful tool that has saved me countless hours in my data science and visualization projects. Whether you’re plotting functions, generating signals, or creating evenly spaced data points for analysis, linspace provides a clean and intuitive way to achieve your goals.

Other Python articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.