Kodeclik Blog


Numpy Linspace numpy.linspace() in Python

The Numpy Linspace numpy.linspace() function is a part of the Python numpy library that enables us to generate an array of evenly spaced elements between two specified, start and stop, values. It takes three parameters – start, stop and num (num is optional), where start and stop are the beginning and ending limits (lowest & highest) points respectively for the sequence; and num is the number of samples we want to generate between these two limits (including both).

Example 1: start and stop values with samples unspecified

Let us assume we are exploring temperatures in a given location and they range from 55F to 85F. Let us assume we would like to generate temperatures within the range [55,85]. Here is the simplest way to use numpy.linspace():
By default, when num is not specified (recall that it is optional), it is assumed to be 50. Thus, the above line generates 50 values from 55 to 85, inclusive:
Note that linspace() finds the stepsize automatically (i.e., this is not a parameter). All you need to supply is the number of values you need.

Example 2: start and stop values with number of samples given

For instance, because 85-55=30, we specify num=31 to make numpy.linspace() output integers from 55 to 85. Here is the program for doing so:
This generates:
Indeed we get integer values but note that they are all output as floats.

Example 3: endpoint exclusion

You can also use endpoint=False which means to not include the “stop” value. Lets use that and also reduce the num from 31 to 30 (which should again make the generated values to be integral values):
The output is:

Example 4: returning stepsize

One additional feature of linspace is, because we only specify the number of values we need and not the step size, we can ask it to return the stepsize for us (by specifying retstep=True, i.e., retstep refers to “return step”). Here is how that works:
The output will be:
Note that we get a tuple of two components, so we can unpack it like so:
The output will be:

Example 5: multidimensional arrays

A final feature in numpy.linspace() is that you can use it to generate multidimensional arrays of evenly spaced values:
In the above, we are essentially creating three series of values, from 1 to 10, from 2 to 20, and from 4 to 76. The output is as expected:
One of the main uses for numpy linspace() is plotting graph data points on a graph using matplotlib or other plotting libraries in Python. By using linspace(), you can quickly create an array with an even distribution of values that can be used as data points for plotting graphs or other visualizations.

Example 6: Plotting curves

Let us use these concepts to approximate a curve, for instance a sine curve. The numpy.linspace() function is useful for generating evenly spaced values for various applications, such as creating x-values for plot functions in data visualization libraries like Matplotlib.
Consider the following program:
And its output will be:
You will see that the plot is a bit chunky (more on that below).
To understand the above program, we first import the necessary libraries: numpy for numerical operations and matplotlib.pyplot for plotting.
We then use np.linspace(0, 4np.pi, 10) to generate 10 evenly spaced values between 0 and 4pi. These values will be used as the x-coordinates for plotting the sine curve. Next, we calculate the sine values for each of the evenly spaced x values using np.sin(x).
We use plt.plot(x, y) to plot the x and y values, which will create the sine curve. We add a title, x-axis label, and y-axis label to the plot using plt.title(), plt.xlabel(), and plt.ylabel(), respectively. Finally, we call plt.show() to display the plot.
The resulting plot will show an approximate sine curve with 100 evenly spaced points between 0 and 2*pi on the x-axis, and the corresponding sine values on the y-axis.
Now back to how the plot looks, it is looking chunky or jagged because there are not enough evenly spaced points being sampled to create a smooth sine curve. If we increase the number of points from 10 to say 60:
Note that we have changed only one line - from 10 points to 60 points. The output will be:

Example 7: Plotting a grid of points

Let us use numpy.linspace() to plot a grid of evenly spaced points. Consider the below program:
To understand the program above, again we first import the necessary libraries: numpy for numerical operations and matplotlib.pyplot for plotting.
We then use np.linspace(-5, 5, 20) to generate 20 evenly spaced values between -5 and 5 for both x and y coordinates. Next, we use np.meshgrid(x, y) to create a meshgrid from the x and y values, which will give us the coordinates for a 2D grid of points.
We use plt.scatter(X, Y, s=10, c='b', marker='o') to plot the grid of points, where X and Y are the meshgrid coordinates, s=10 sets the size of the markers, c='b' sets the color to blue, and marker='o' sets the marker style to circles. We add a title, x-axis label, and y-axis label to the plot using plt.title(), plt.xlabel(), and plt.ylabel(), respectively. Finally, we call plt.show() to display the plot.
The resulting plot will show a 2D grid of 20x20 evenly spaced points between -5 and 5 on both the x and y axes, with blue circular markers:

Example 8: Plotting a 2D spiral

Next, we use np.linspace() to generate 1000 evenly spaced values between 0 and 8π for the angle theta. We then use it in a program to draw a spiral:
Note that the program uses the radius r as a function of theta to create a spiral pattern. The x and y coordinates are calculated from r and theta, and then plotted to create a spiral curve. The output will be:

Numpy linspace arguments

Finally, to summarize, below is the list of all numpy.linspace() arguments, along with their descriptions and whether they are required or optional:
1. start (required): The starting value of the sequence.
2. stop (required): The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded.
3. num (optional): Number of samples to generate. Default is 50. Must be non-negative.
4. endpoint (optional): If True, stop is the last sample. Otherwise, it is not included. Default is True.
5. retstep (optional): If True, return (samples, step), where step is the spacing between values. Default is False.
6. dtype (optional): The data type of the output array. If not given, the data type will be inferred from start and stop.
7. axis (optional): If start and stop are arrays, this specifies the axis along which the sequence will be generated. If 0, the sequence is added at the beginning, if -1, it's added at the end. Default is 0.
The start and stop arguments are required and represent the beginning and end of the interval over which the evenly spaced values will be generated.
The num argument is optional and specifies the number of values to generate. If not provided, the default value of 50 is used.
The endpoint argument is optional and determines whether the stop value is included in the generated sequence or not. By default, it is set to True, meaning the stop value is included.
The retstep argument is optional and, if set to True, returns a tuple containing the generated array and the step size between consecutive values.
The dtype argument is optional and specifies the data type of the output array. If not provided, the data type is inferred from the start and stop values.
The axis argument is optional and is used when start and stop are arrays, specifying the axis along which the sequence should be generated.

Summary

In closing, If you're looking for a quick and easy way to generate an array containing evenly spaced numbers within a given interval, then using numpy's linspace() function is ideal! This is useful whether you wish to generate data or use the data for plotting pretty pictures!
The main takeaway from this blogpost is that numpy.linspace() takes 3 parameters: start & stop which are used as lower & upper bounds respectively; the upper bound can be inclusive or exclusive; and num which specifies how many elements should be generated within those limits (defaulted at 50). Knowing how this function works can certainly come in handy when working with data visualizations or statistical pattern finding! So give it a try today!
If you liked this blogpost, checkout how to scale and rotate a vector in Python.
If you liked this blogpost, checkout our blogpost on comparing two dictionaries. Also learn how to unpack a dictionary into variables.
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.