How to Create Seaborn Line Plots
Seaborn is a highly efficient visualization tool available in Python for creating stunning plots. It uses and is based on the matplotlib module.
A line plot is one of the most basic plots of this module. It is generally used to keep track of something with respect to time. It can also have a continuous observation on one axis and a categorical value on the other.
In this tutorial, we will learn how to create a line plot using the seaborn module in Python.
We will use the seaborn.lineplot()
function to create a line plot. The following code shows how to use this function and create a simple line plot.
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
{"Price 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day": [1, 2, 3, 4, 5, 6, 7, 8]}
)
s1 = sns.lineplot(x="Day", y="Price 1", data=df, color="red")
We can use different arguments to customize the plot. For example, the color
argument can change the color of the line in the plot.
The style
and hue
are heavily used when we need to group variables and show the variation with respect to the variables. This can be useful when we want to plot categorical values on a single plot and allows us to plot multiple lines on a single figure.
For example,
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"Price": [7, 1, 5, 6, 3, 10, 5, 8],
"Product": ["C1", "C2", "C1", "C2", "C1", "C2", "C1", "C2"],
"Day": [1, 1, 2, 2, 3, 3, 4, 4],
}
)
s = sns.lineplot(x="Day", y="Price", data=df, hue="Product")
We can also have multiple line plots on top of each other. This method also allows us to plot multiple observations on the same plot regardless of the categories.
See the code below.
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"Price 1": [7, 1, 5, 6, 3, 10, 5, 8],
"Price 2": [1, 2, 8, 4, 3, 9, 5, 2],
"Day": [1, 2, 3, 4, 5, 6, 7, 8],
}
)
s1 = sns.lineplot(x="Day", y="Price 1", data=df, color="red")
s2 = sns.lineplot(x="Day", y="Price 2", data=df, color="blue")
plt.legend(labels=["Price1", "Price2"])
When we are working with multiple lines, it is better to add a legend to the plot, which can help differentiate both lines. The matplotlib.pyplot.legend()
function in the above code is used to explicitly add a legend in which we can specify our labels also.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn