Clamp Function

Get introduced to the clamp scale and look at some examples.

We'll cover the following

Introduction

Let’s look at an important function, the clamp function. It is very useful when dealing with scales because it helps us to clamp/attach our domain to a given range. In a linear and logarithmic scale, if we give a value outside the domain, it will interpolate the range value outside our specified range, which is not desirable.

Example

To see how a scale can give a value outside the specified range, let’s look at an example of a linear scale.

Console
Code without the clamp function

Explanation

Let’s try to understand the above code by looking into the following explanation.

In line 4 of the above code, if we give a value, 12, which is outside of our domain, we will get the value 4.8 which lies outside of our range. It is not preferred in data visualization if the value sits outside of our specified range.

Can we overcome this problem? Yes, we can! We are going to use the clamp function to clamp our domain, [0-10], to the specified range, [0-4]. To see how this will work, let’s look at the following code.

Console
Clamp function code

Given below is an explanation to help you understand the above code.

By default, the clamp has a Boolean value of false. By setting it to true in line 4, we have restricted the range. If we give a value outside domain [0-10], it would clamp it to range [0-4] as seen in line 5. By passing 12 to cgpaconv(), it would give us 4 which lies inside our specified range.