Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (2024)

In this Python data visualization tutorial, we will learn how to create line plots with Seaborn. First, we’ll start with the simplest example (with one line) and then we’ll look at how to change the look of the graphs, and how to plot multiple lines, among other things.

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (1)

  • Save

Note, the above plot was created using Pandas read_html to scrape data from a Wikipedia table and Seaborn’s lineplot method. All code, including for creating the above plot, can be found in a Jupyter notebook (see towards the end of the post).

Table of Contents

Data Visualization Introduction

Now, when it comes to visualizing data, it can be fun to think of all the flashy and exciting methods to display a dataset. However, if we’re trying to convey information, creating fancy and cool plots isn’t always the way to go.

In fact, one of the most powerful ways to show the relationship between variables is the simple line plot. First, we are going to look at how to quickly create a Seaborn line plot. After that, we will cover some more detailed Seaborn line plot examples.

Simple Seaborn Line Plot

To create a Seaborn line plot we can follow the following steps:

  1. Import data (e.g., with pandas)
import pandas as pddf = pd.read_csv('ourData.csv', index_col=0)

2. Use the lineplot method:

import seaborn as snssns.lineplot('x', 'y', data=df)

Importantly, in 1) we need to load the CSV file, and in 2) we need to input the x- and y-axis (e.g., the columns with the data we want to visualize). More details, on how to use Seaborn’s lineplot, follows in the rest of the post.

Prerequisites

Now, before continuing with simulating data to plot, we will briefly touch on what we need to follow this tutorial. Obviously, we need to have Python and Seaborn installed. Furthermore, we will need to have NumPy as well. Note, Seaborn is depending on both Seaborn and NumPy. This means that we only need to install Seaborn to get all packages we need. As many Python packages, we can install Seaborn with pip or conda. If needed, there’s a post about installing Python packages with both pip and conda, available. Check it out.

Simulate Data

In the first Seaborn line graph examples, we will use data that are simulated using NumPy. Specifically, we will create two response variables (x & y) and a time variable (day).

import numpy as np# Setting a random seed for reproducibilitynp.random.seed(3)# Numpy Arrays for means and standard deviations# for each day (variable x)mus_x = np.array([21.1, 29.9, 36.1])sd_x = np.array([2.1, 1.94, 2.01])# Numpy Arrays for means and standard deviations# for each day (variable y)mus_y = np.array([64.3, 78.4, 81.1])sd_y = np.array([2.2, 2.3, 2.39])# Simulating data for the x and y response variablesx = np.random.normal(mus_x, sd_x, (30, 3))y = np.random.normal(mus_y, sd_y, (30, 3))# Creating the "days"day= ['d1']*30 + ['d2']*30 + ['d3']*30# Creating a DataFrame from a Dictionarydf = pd.DataFrame({'Day':day, 'x':np.reshape(x, 90, order='F'), 'y':np.reshape(y, 90, order='F')})df.head()

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (2)

  • Save

In the code chunk above, we used NumPy to create some data (refer to the documentation for more information) and we then created a Pandas DataFrame from a dictionary. Usually, of course, we read our data from an external data source and we’ll have look at how to do this, as well, in this post. Here are some useful articles:

  • How to read and write Excel (xlsx) files in Python with Pandas
  • How to read SAS files with Pandas
  • How to read SPSS (.sav) files in Python with Pandas
  • How to read STATA files in Python with Pandas

Basic Seaborn Line Plot Example

Now, we are ready to create our first Seaborn line plot and we will use the data we simulated in the previous example. To create a line plot with Seaborn we can use the lineplot method, as previously mentioned. Here’s a working example plotting the x variable on the y-axis and the Day variable on the x-axis:

import seaborn as snssns.lineplot('Day', 'x', data=df)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (3)

Here we started with the simplest possible line graph using Seaborn’s lineplot. For this simple graph, we did not use any more arguments than the obvious above. Now, this means that our line plot also got the confidence interval plotted. In the next Seaborn line plot example, we are going to remove the confidence interval.

Removing the Confidence Intervall from a Seaborn Line Plot

In the second example, we are going to remove the confidence interval from the Seaborn line graph. This is easy to do we just set the ci argument to “None”:

sns.lineplot('Day', 'x', ci=None, data=df)

This will result in a line graph without the confidence interval band, that we would otherwise get:

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (4)

  • Save

Adding Error Bars in Seaborn lineplot

Expanding on the previous example, we will now, instead of removing, changing how we display the confidence interval. Here, we will change the style of the error visualization to bars and have them to display 95 % confidence intervals.

sns.lineplot('Day', 'x', ci=95, err_style='bars', data=df)

As evident in the code chunk above, we used Seaborn lineplot and we used the err_style argument with ‘bars’ as paramenter to create error bars. Thus, we got this beautiful line graph:

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (5)

  • Save

Note, we can also use the n_boot argument to customize how many boostraps we want to use when calculating the confidence intervals.

Changing the Color of a Seaborn Line Plot

In this Seaborn line graph example, we are going to further extend on our previous example but we will be experimenting with color. Here, we will add the color argument and change the color of the line and error bars to red:

sns.lineplot('Day', 'x', ci=95, color="red", err_style='bars', data=df)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (6)

  • Save

Note, we could experiment a bit with different colors to see how this works. When creating a Seaborn line plot, we can use most color names we can think of. Finally, we could also change the color using the palette argument but we’ll do that later when creating a Seaborn line graph with multiple lines.

Adding Markers (dots) in Seaborn lineplot

In this section, we are going to look at a related example. Here, however, instead of changing the color of the line graph, we will add dots:

sns.lineplot('Day', 'x', ci=None, marker='o', data=df)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (7)

  • Save

Notice how we used the marker argument here. Again, this is something we will look at more in-depth when creating Seaborn line plots with multiple lines.

Seaborn Line Graphs with Multiple Lines Example

First, we are going to continuing working with the dataset we previously created. Remember, there were two response variables in the simulated data: x, y. If we want to create a Seaborn line plot with multiple lines on two continuous variables, we need to rearrange the data.

sns.lineplot('Day', 'value', hue='variable', data=pd.melt(df, 'Day'))

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (8)

  • Save

In the code, we use the hue argument and here we put ‘variable’ as a paremter because the data is transformed to long format using the melt method. Note, we can change the names of the new columns:

df2 = pd.melt(df, 'Day', var_name='Measure', value_name='Value')sns.lineplot('Day', 'Value', hue='Measure', data=df2)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (9)

  • Save

Note, it of course better to give the new columns better variable names (e.g., if we’d have a real dataset to create a Seaborn line plot we’d probably know). We will now continue learning more about modifying Seaborn line plots.

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (10)

  • Save

On a related topic, see the post about renaming columns in Pandas for information about how to rename variables.

How to Change Line Types of a Seaborn Plot with Multiple Lines

In this example, we will change the line types of the Seaborn line graph. Here’s how to change the line types:

sns.lineplot('Day', 'Value', hue='Measure', style='Measure', data=df2)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (11)

  • Save

Using the new Pandas dataframe that we created in the previous example, we added the style argument. Here, we used the Measure column (x, y) to determine the style. Additionally, we can choose the style of the lines using the dashes argument:

sns.lineplot('Day', 'Value', hue='Measure', style='Measure', dashes=[(1, 1), (5, 10)], data=df2)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (12)

  • Save

Notice, how we added two tuples to get one loosely dashed line and one dotted line. For more, line styles see the Matplotlib documentation. Changing the line types of a Seaborn line plot may be important if we are to print the plots in black and white as it makes it easier to distinguish the different lines from each other.

Changing the Color of a Seaborn Line Plot with Multiple Lines

In this example, we are going to build on the earlier examples and change the color of the Seaborn line plot. Here we will use the palette argument (see here for more information about Seaborn palettes).

pal = sns.dark_palette('purple',2)sns.lineplot('Day', 'Value', hue='Measure', style='Measure', palette=pal, dashes=[(1, 1), (5, 10)], data=df2)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (13)

  • Save

Note that we first created a palette using the dark_palette method. The first argument is probably obvious but the second is due to that we have to lines in our Seaborn line plot. If we, on the other hand, have 3 lines we’d change this to 3, of course.

Adding Dots to a Seaborn Line plots with Multiple Lines

Now, adding markers (dots) to the line plot, when having multiple lines, is as easy as with one line. Here we just add the markers=True:

sns.lineplot('Day', 'Value', hue='Measure', style='Measure', markers=True, dashes=[(1, 1), (5, 10)], data=df2)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (14)

  • Save

Notice how we get crosses and dots as markers? We can, of course, if we want change this to only dots:

sns.lineplot('Day', 'Value', hue='Measure', style='Measure', markers=['o','o'], dashes=[(1, 1), (5, 10)], data=df2)

Note, it is, of course, possible to change the markers to something else. Refer to the documentation for possible marker styles.

Seaborn Line plot with Dates on the x-axis: Time Series

Now, in this example, we are going to have more points on the x-axis. Thus, we need to work with another dataset and we are going to import a CSV file to a Pandas dataframe:

data_csv = 'https://vincentarelbundock.github.io/Rdatasets/csv/ISLR/Wage.csv'df = pd.read_csv(data_csv, index_col=0)df.head()

Refer to the post about reading and writing .csv files with Pandas for more information about importing data from CSV files with Pandas.

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (15)

  • Save

In the image above, we can see that there are multiple variables that we can group our data by. For instance, we can have a look at wage, over time, grouping by education level:

sns.lineplot('year', 'wage', ci=None, hue='education', data=df)

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (16)

  • Save

Now, we can clearly see that the legend, in the above, line chart is hiding one of the lines. If we want to move it we can use the legend method:

lp = sns.lineplot('year', 'wage', ci=None, hue='education', data=df)lp.legend(loc='upper right', bbox_to_anchor=(1.4, 1))

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (17)

  • Save

Seaborn Line Plots with 2 Categories using FacetGrid:

If we, on the other hand, want to look at many categories at the same time, when creating a Seaborn line graph with multiple lines, we can use FacetGrid:

g = sns.FacetGrid(df, col='jobclass', hue='education')g = g.map(sns.lineplot, 'year', 'wage', ci=None).add_legend()

First, in the above code chunk, we used FacetGrid with our dataframe. Here we set the column to be jobclass and the hue, still, to be education. In the second line, however, we used map and here we need to put in the variable that we want to plot aagainst each other. Finally, we added the legend (add_legend()) to get a legend. This produced the following line charts:

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (18)

  • Save

That was it, we now have learned a lot about creating line charts with Seaborn. There are, of course, a lot of more ways we can tweak the Seaborn plots (see the lineplot documentation, for more information).

Additionally, if we need to change the fig size of a Seaborn plot, we can use the following code (added before creating the line graphs):

import matplotlib.pyplot as pltfig = plt.gcf()fig.set_size_inches(12, 8)

Finally, refer to the post about saving Seaborn plots if the graphs are going to be used in a scientific publication, for instance.

Summary

In this post, we have had a look at how to create line plots with Seaborn. First, we had a look at the simplest example with creating a line graph in Python using Seaborn: just one line. After that, we continued by using some of the arguments of the lineplot method. That is, we learned how to:

  • remove the confidence interval,
  • add error bars,
  • change the color of the line,
  • add dots (markers)

In the last sections, we learned how to create a Seaborn line plot with multiple lines. Specifically, we learned how to:

  • change line types (dashed, dotted, etc),
  • change color (using palettes)
  • add dots (markers)

In the final example, we continued by loading data from a CSV file and we created a time-series graph, we used two categories (FacetGrid) to create two two-line plots with multiple lines. Of course, there are other Seaborn methods that allows us to create line plots in Python. For instance, we can use catplot and pointplot, if we’d like to. All code examples can be found in this Jupyter notebook.

Additional Resources

Here are some additional resources that may come in handy when it comes to line plots, in particular, but also in general when doing data visualization in Python (or any other software). First, you will find some useful web pages on how to making effective data visualizations, communicating clearly, and what you should and not should do. After that, you will find some open access-publications about data visualization. Add a comment below, if there’s a resource missing here.

Scientific Publications

Peebles, D., & Ali, N. (2009). Differences in comprehensibility between three-variable bar and line graphs. Proceedings of the Thirty-First Annual Conference of the Cognitive Science Society, 2938–2943. Retrieved from http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.412.4953

Peebles, D., & Ali, N. (2015). Expert interpretation of bar and line graphs: The role of graphicacy in reducing the effect of graph format. Frontiers in Psychology, 6(OCT), 1–11. https://doi.org/10.3389/fpsyg.2015.01673

Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines) (2024)

FAQs

How do you plot a line graph in Seaborn? ›

Using size parameter to plot multiple line plots in Seaborn. We can even use the size parameter of seaborn. lineplot() function to represent the multi data variable relationships with a varying size of line to be plotted. So it acts as a grouping variable with different size/width according to the magnitude of the data ...

How do I change my line style in Seaborn? ›

Customize line style by passing a dict mapping to “dashes”

“dashes” parameter is used along with “style” parameter. In a dictionary, you set a “category to style” mapping. The style will be in a tuple (as discussed in above section). Pass this dictionary mapping to “dashes” parameter.

What is hue in Lineplot? ›

The column passed to hue parameter is used as a grouping column. A single line is now grouped into multiple lines as per the number of categories in that column. And, the groups are shown as different colored lines.

How do I plot multiple lines in a csv file in Python? ›

MatPlotLib with Python
  1. Set the figure size and adjust the padding between and around the subplots.
  2. Create a list of columns to fetch the data from a . CSV file. ...
  3. Read the data from the . CSV file.
  4. Plot the lines using df. plot() method.
  5. To display the figure, use show() method.
22 Sept 2021

How do you plot more than one graph in Python? ›

  1. 📍 Tip 1: plt. subplots() One easy way to plot multiple subplots is to use plt.subplots() . ...
  2. 📍 Tip 2: plt.subplot() Another way to visualise multiple graphs is to use plt.subplot() without s at the end). The syntax is slightly different from before: plt.figure(figsize=(10,4)) ...
  3. 📍 Tip 3: plt. tight_layout()
18 Oct 2021

How do you plot a line in Python? ›

To create a line plot, pass an array or list of numbers as an argument to Matplotlib's plt. plot() function. The command plt. show() is needed at the end to show the plot.

What does a line plot look like? ›

What is a Line Plot? A Line plot can be defined as a graph that displays data as points or check marks above a number line, showing the frequency of each value. Here, for instance, the line plot shows the number of ribbons of each length.

How do you plot the time series in Seaborn? ›

MatPlotLib with Python
  1. Set the figure size and adjust the padding between and around the subplots.
  2. Create a Pandas dataframe, df, to hold a date_time series "time" and another variable data, speed.
  3. Make a Seaborn line plot with the data, "time" and "speed"
  4. Rotate the tick params by 45.
22 Sept 2021

What is a line plot in math? ›

A line plot is a graph that displays data using a number line. To create a line plot, ​first create a number line that includes all the values in the data set. Next, place an X (or dot) above each data value on the number line.

How do I change my figure size in Seaborn? ›

Introduction
  1. manually create an Axes object with the desired size.
  2. pass some configuration paramteters to seaborn so that the size you want is the default.
  3. call a method on the figure once it's been created.
  4. pass hight and aspect keywords to the seaborn plotting function.
  5. use the matplotlib. ...
  6. use the matplotlib.
11 Feb 2021

How do I make a dashed line in Matplotlib? ›

x: X-axis points on the line. y: Y-axis points on the line. linestyle: Change the style of the line.

What is point plot? ›

A point plot represents an estimate of central tendency for a numeric variable by the position of the dot and provides some indication of the uncertainty around that estimate using error bars.

Which method is called to create a line graph in Seaborn? ›

lineplot() Draw a line plot with the possibility of several semantic groupings. The relationship between x and y can be shown for different subsets of the data using the hue, size, and style parameters.

What is ci in Seaborn? ›

The seaborn ci code you posted simply computes the percentile limits. This interval has a defined mean of 50 (median) and a default range of 95% confidence interval. The actual mean, the standard deviation, etc. will appear in the percentiles routine. Follow this answer to receive notifications.

How do you graph multiple lines? ›

So let me now show you how to plot multiple data series or lines onto the same graph. Right click on

How do I fill multiple lines in matplotlib? ›

With the use of the fill_between() function in the Matplotlib library in Python, we can easily fill the color between any multiple lines or any two horizontal curves on a 2D plane.

How do you plot multiple lines in MATLAB? ›

Plot Multiple Lines

By default, MATLAB clears the figure before each plotting command. Use the figure command to open a new figure window. You can plot multiple lines using the hold on command. Until you use hold off or close the window, all plots appear in the current figure window.

Which function is used to draw multiple plots in one figure? ›

You can display multiple axes in a single figure by using the tiledlayout function. This function creates a tiled chart layout containing an invisible grid of tiles over the entire figure. Each tile can contain an axes for displaying a plot.

How do you plot 4 subplots in Python? ›

To create multiple plots use matplotlib. pyplot. subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.

How do you display multiple figures in Python? ›

The easiest way to display multiple images in one figure is use figure(), add_subplot(), and imshow() methods of Matplotlib. The approach which is used to follow is first initiating fig object by calling fig=plt. figure() and then add an axes object to the fig by calling add_subplot() method.

› seaborn-multiple-line-plot... ›

Multiple line plot is graph plot between 2 attributes consisting of numeric data. Seaborn in Python is used for plotting multiple line plot.
Line plot: Line plots can be created in Python with Matplotlib's pyplot library. To build a line plot, first import Matplotlib. It is a standard convention ...
This tutorial explains how we can plot multiple lines in Python Matplotlib and set a different color for each line in the figure.

How do you make a subplot in Seaborn? ›

You can use the following basic syntax to create subplots in the seaborn data visualization library in Python: #define dimensions of subplots (rows, columns) fig, axes = plt. subplots(2, 2) #create chart in each subplot sns. boxplot(data=df, x='team', y='points', ax=axes[0,0]) sns.

How do you plot the time series in Seaborn? ›

MatPlotLib with Python
  1. Set the figure size and adjust the padding between and around the subplots.
  2. Create a Pandas dataframe, df, to hold a date_time series "time" and another variable data, speed.
  3. Make a Seaborn line plot with the data, "time" and "speed"
  4. Rotate the tick params by 45.
22 Sept 2021

How do you put markers on Seaborn Lineplot? ›

You can also plot markers on a Seaborn line plot. Markers are special symbols that appear at the places in a line plot where the values for x and y axes intersect. To plot markers, you have to pass a list of symbols in a list to the markers attribute. Each symbol corresponds to one line plot.

How do I increase my plot size in Seaborn? ›

To adjust the figure size of the seaborn plot we will use the subplots function of matplotlib. pyplot.

How do I show two graphs side by side in Python? ›

How do you plot two graphs side by side in Python?
  1. Creating x, y1, y2 points using numpy.
  2. With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method.
  3. Plot the line using x and y1 points, using the plot() method.
  4. Set up the title, label for X and Y axes for Figure 1, using plt.

How do I plot multiple variables in Matplotlib? ›

In Matplotlib, we can draw multiple graphs in a single plot in two ways.
...
Multiple Plots using subplot () Function
  1. nrows, ncols: These gives the number of rows and columns respectively. ...
  2. sharex, sharey: These parameters specify about the properties that are shared among a and y axis.
3 Jan 2021

How do you plot multiple columns in a Dataframe in Python? ›

To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.
...
Approach:
  1. Import module.
  2. Create or load data.
  3. Convert to dataframe.
  4. Using plot() method, specify a single column along X-axis and multiple columns as an array along Y-axis.
  5. Display graph.
30 Dec 2021

How do you make a time series plot? ›

To create a time series plot in Excel, first select the time (DateTime in this case) Column and then the data series (streamflow in this case) column. Next, click on the Insert ribbon, and then select Scatter. From scatter plot options, select Scatter with Smooth Lines as shown below.

How do I add a title to Seaborn? ›

To add a title to a single seaborn plot, you can use the . set() function. To add an overall title to a seaborn facet plot, you can use the . suptitle() function.

How do I change my Seaborn theme? ›

You can set themes using the set_style() function of seaborn library.

What does a line plot look like? ›

What is a Line Plot? A Line plot can be defined as a graph that displays data as points or check marks above a number line, showing the frequency of each value. Here, for instance, the line plot shows the number of ribbons of each length.

How do you plot a line in Python? ›

To create a line plot, pass an array or list of numbers as an argument to Matplotlib's plt. plot() function. The command plt. show() is needed at the end to show the plot.

What is point plot? ›

A point plot represents an estimate of central tendency for a numeric variable by the position of the dot and provides some indication of the uncertainty around that estimate using error bars.

How do I change font size in Seaborn? ›

Note that the default value for font_scale is 1. By increasing this value, you can increase the font size of all elements in the plot.

How do I change my figure size in Seaborn Facetgrid? ›

You can use g. figure. set_size_inches(20, 12) to change the size, e.g. just before saving.

How do you change the size of a figure in Python? ›

Set the figsize Argument

First off, the easiest way to change the size of a figure is to use the figsize argument. You can use this argument either in Pyplot's initialization or on an existing Figure object. Here, we've explicitly assigned the return value of the figure() function to a Figure object.

› how-to-set-a-seaborn-ch... ›

It has a parameter called figsize which takes a tuple as an argument that contains the height and the width of the plot. It returns the figure and the array of ...
In a previous tutorial, we discussed the Seaborn heatmap and we saw how it can render high-level graphs and attractive statistical drawings. Among numerous plot...

Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 5538

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.