Lineplot using Seaborn in Python


Data analysis and machine learning both require data visualisation. Seaborn is one of the most sophisticated and user-friendly Python modules for building attractive, useful visualisations. In this tutorial, we'll go in-depth on how to make line plots in Python using the Seaborn package. A line plot is a basic data visualisation graphic that shows information as a collection of markers, or data points, connected by straight line segments.

Introduction to Line Plots in Seaborn

The lineplot() function from Seaborn provides a straightforward, understandable interface for creating eye-catching and useful line charts. It is possible to use it to monitor alterations over time for one or more groups.

A simple function signature is shown below −

seaborn.lineplot(x=None, y=None, hue=None, data=None, palette=None, markers=None, style=None, dashes=None, linewidth=None)

Getting Started with Seaborn Line Plots

The Seaborn and Matplotlib libraries must be set up in your Python environment before you can proceed. If not, pip can be used to install them:

pip install seaborn matplotlib

After that, import the required libraries −

import seaborn as sns
import matplotlib.pyplot as plt

Example 1: Basic Line Plot

Let's use Seaborn to make a simple line plot:

import seaborn as sns
import matplotlib.pyplot as plt

# Simple dataset
days = list(range(0, 22, 3))
temperature = [25, 28, 30, 32, 33, 33, 34, 35, 36, 34, 33]

# Create lineplot
sns.lineplot(x=days, y=temperature)

# Show the plot
plt.show()

The temperature is plotted using this code over a number of days. The plot is shown by the show() method.

Example 2: Line Plot from DataFrame

A Pandas DataFrame can be used to immediately construct a line plot:

import seaborn as sns
import pandas as pd

# Create a simple DataFrame
data = pd.DataFrame({
   'Days': list(range(1, 11)),
   'Temperature': [22, 24, 25, 28, 30, 29, 31, 32, 33, 34]
})

# Create lineplot
sns.lineplot(x='Days', y='Temperature', data=data)

# Show the plot
plt.show()

This programme produces a DataFrame containing data for "Days" and "Temperature" and then graphs it using the lineplot() method from Seaborn.

Example 3: Multiple Line Plots

Using the 'hue' argument, you can plot numerous lines on the same plot −

import seaborn as sns
# Multiple line plot
data = pd.DataFrame({
   'Days': list(range(1, 11)),
   'Temperature': [22, 24, 25, 28, 30, 29, 31, 32, 33, 34],
   'DewPoint': [10, 11, 12, 14, 15, 15, 16, 17, 18, 18]
})

sns.lineplot(x='Days', y='value', hue='variable', data=pd.melt(data, ['Days']))

plt.show()

'Temperature' and 'DewPoint' are plotted over 'Days' in this example. The DataFrame is reshaped to make it acceptable for the visualisation using the pd.melt() function.

Example 4: Line Plot with Confidence Interval

Additionally, Seaborn offers a confidence interval visualisation option for the distribution of data:

import seaborn as sns
# Sample data
import numpy as np
np.random.seed(0)
data = pd.DataFrame(data=np.random.randn(100, 3), columns=['B1', 'B2', 'B3']).cumsum()

# Add a column with constant value
data['Days'] = pd.Series(list(range(len(data))))

# Multiple line plot with confidence interval
sns.lineplot(x="Days", y="value", hue="variable",
             data=pd.melt(data, ['Days']))

plt.show()

The confidence interval is shown by the dark area surrounding each line in this graphic.

Example 5: Line Plot with Different Markers and Line Styles

By utilising the'style' argument to provide various markers and line styles, you may distinguish each line:

import seaborn as sns
data = pd.DataFrame({
   'Time': list(range(1, 11)),
   'Measurement1': np.random.randn(10).cumsum(),
   'Measurement2': np.random.randn(10).cumsum()
})

sns.lineplot(x='Time', y='value', hue='variable', style='variable', markers=True, dashes=False, 
             data=pd.melt(data, ['Time']))

plt.show()

This script employs a solid line style and gives each line a different marker.

Example 6: Customizing Line Plot with Matplotlib Functions

Using Matplotlib's functions, Seaborn plots can be further customised:

import seaborn as sns
# Generate data
data = pd.DataFrame({
   'Time': list(range(1, 11)),
   'Measurement1': np.random.randn(10).cumsum(),
   'Measurement2': np.random.randn(10).cumsum()
})

sns.lineplot(x='Time', y='value', hue='variable', data=pd.melt(data, ['Time']))

plt.title('Time Series Plot')
plt.xlabel('Time (s)')
plt.ylabel('Measurements')
plt.grid(True)
plt.show()

This script enhances the plot with a title, labels for both axes, and a grid.

Conclusion

Python's lineplot() function by Seaborn is a useful resource for designing informative and aesthetically beautiful line charts. It is a dependable option for data scientists and analysts due to its capacity to function without a hitch with Pandas DataFrames and integrate with Matplotlib for more customisation.

To discover underlying patterns and trends, remember that visualising your data is crucial. Seaborn offers the tools required to make this process simple and efficient. You may uncover insights and share tales that are hidden in your data by using the proper visualisation strategy.

Updated on: 18-Jul-2023

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements