When it comes to reusing code in Python, it all starts and ends with the humble “function”.
Functions
Functions wrap up reusable pieces of code — they help you apply the Do Not Repeat Yourself (DRY) principle.
Functions can be designed to accept arguments as input and return values.
Code Reuse
Code Reuse refers to the concept of writing a single function and re-using it multiple times and minimizing duplication.
Ideally, code reuse should be easy to implement, and any stable, functional code could freely be reused when writing the code for specific features or building a new software application.
In this article, we will be focusing on how to reuse code on various data visualization techniques using functions. Let’s quickly talk about what is Data Visualization.
Data Visualization
It is a way to express data in a visual context so that patterns, correlations, trends between the data can be easily understood. Data Visualization helps in finding hidden insights in the raw data.
The base dataset that we will be using to understand code reusability using functions, is the iris dataset
which we will import from sklearn
.
Iris Flower Data Set
The data set consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features were measured from each sample: the length and the width of the sepals and petals, in centimeters.
Let’s get into the code in a swift.
- We can quickly load iris dataset from sklearn module
import sklearn
from sklearn import datasets
iris = datasets.load_iris()
Now, we will create a pandas
dataframe and load the iris dataset, our main focus is on features from the data so we will name the columns according to the feature names, we can get them using iris.feature_names
import pandas as pd
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
- We will be using
matplotlib
module to plot a scatter plot, let’s import it
import matplotlib.pyplot as plt
Define Function
Below code is a function defined to take 2 features as input and returns a scatter plot for the desired features we want as output, in our case those features are
- sepal_length
- sepal_width
- petal_length
- petal_width
Now we’re all set to get into action, I mean run the code and visualize a scatter plot for different features using our own defined function named scatter_plot
By following the above approach, it provides us to plot the scatter plot for different features, without writing the same code again and again every time we to want look and work around with features.
Code Reuse using function aims to save time and resources, that allows a more sustainable way of working.
In Software Development, there is already a well-established concept around reusability.
This approach is followed majorly in vast areas of software development,
reducing users’ work and the risk of making mistakes which is very crucial.