The Wayback Machine - https://web.archive.org/web/20241113233314/https://www.geeksforgeeks.org/time-series-plot-or-line-plot-with-pandas/
Open In App

Time Series Plot or Line plot with Pandas

Last Updated : 26 Nov, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Create a Pandas DataFrame from Lists

Pandas is an open-source library used for data manipulation and analysis in Python. It is a fast and powerful tool that offers data structures and operations to manipulate numerical tables and time series. Examples of these data manipulation operations include merging, reshaping, selecting, data cleaning, and data wrangling. This library allows importing data from various file formats like SQL, JSON, Microsoft Excel, and comma-separated values. This article explains how to use the pandas library to generate a time series plot, or a line plot, for a given set of data.

A line plot is a graphical display that visually represents the correlation between certain variables or changes in data over time using several points, usually ordered in their x-axis value, that are connected by straight line segments. The independent variable is represented in the x-axis while the y-axis represents the data that is changing depending on the x-axis variable, aka the dependent variable.

To generate a line plot with pandas, we typically create a DataFrame* with the dataset to be plotted. Then, the plot.line() method is called on the DataFrame. 

Syntax:

DataFrame.plot.line(x, y)
 

The table below explains the main parameters of the method:

Parameter Value Default Value Use
x Int or string DataFrame indices Set the values to be represented in the x-axis.
y Int or string Remaining columns in DataFrame Set the values to be represented in the y-axis.

Additional parameters include color (specifies the color of the line), title (specifies the title of the plot), and kind (specifies which type of plot to use). The default variable for the “kind” parameter of this method is ‘line’. Therefore, you don’t have to set it in order to create a line plot.

Example 1:

The example illustrates how to generate basic a line plot of a DataFrame with one y-axis variable. Use pandas in Python3 to plot the following data of someone’s calorie intake throughout one week, here is our dataframe.

Code:

Python3




import pandas as pd
  
# Create a list of data to be represented in x-axis
days = [ 'Saturday' , 'Sunday' , 'Monday' , 'Tuesday' ,
        'Wednesday' , 'Thursday' , 'Friday' ]
  
# Create a list of data to be 
# represented in y-axis
calories = [ 1670 , 2011 , 1853 , 2557 ,
            1390 , 2118 , 2063 ]
  
# Create a dataframe using the two lists
df_days_calories = pd.DataFrame(
    { 'day' : days , 'calories' : calories })
  
df_days_calories


Output:

Now, Plotting the variable.

Python3




# use plot() method on the dataframe
df_days_calories.plot( 'day' , 'calories' )
  
# Alternatively, you can use .set_index 
# to set the data of each axis as follows:
# df_days_calories.set_index('day')['calories'].plot();


Output:

Example 2:

This example explains how to create a line plot with two variables in the y-axis.
A student was asked to rate his stress level on midterms week for each school subject on a scale from 1-10 (10 being the highest). He was also asked about his grade on each midterm (out of 20). 

Code:

Python3




import pandas as pd
  
# Create a list of data to
# be represented in x-axis
subjects = [ 'Math' , 'English' , 'History' ,
            'Chem' , 'Geo' , 'Physics' , 'Bio' , 'CS' ]
  
# Create a list of data to be 
# represented in y-axis
stress = [ 9 , 3 , 5 , 1 , 8 , 5 , 10 , 2 ]
  
# Create second list of data
# to be represented in y-axis
grades = [ 15 , 10 , 7 , 8 , 11 , 8 , 17 , 20 ]
  
# Create a dataframe using the three lists
df = pd.DataFrame(list(zip( stress , grades )),
                  index = subjects , 
                  columns = [ 'Stress' , 'Grades' ])
df


Output:

Create a line plot that shows the relationships between these three variables.

Code:

Python3




# use plot() method on the dataframe. 
# No parameters are passed so it uses
# variables given in the dataframe
df.plot()


Output:

An alternative way would be to use gca() method from matplotlib.pyplot library as follows:

Python3




import pandas as pd
import matplotlib.pyplot as plt
  
# Create a list of data
# to be represented in x-axis
subjects = [ 'Math' , 'English' , 'History ',
            'Chem' , 'Geo' , 'Physics' , 'Bio' , 'CS' ]
  
# Create a list of data
# to be represented in y-axis
stress = [ 9, 3 , 5 , 1 , 8 , 5 , 10 , 2 ]
  
# Create second list of data to be represented in y-axis
grades = [ 15, 10 , 7 , 8 , 11 , 8 , 17 , 20 ]
  
# Create a dataframe using the two lists
df_days_calories = pd.DataFrame(
    { 'Subject' : subjects , 
     'Stress': stress , 
     'Grade': grades})
  
ax = plt.gca()
  
#use plot() method on the dataframe
df_days_calories.plot( x = 'Subject' , y = 'Stress', ax = ax )
df_days_calories.plot( x = 'Subject' , y = 'Grade' , ax = ax )


Output:

Example 3:

In this example, we will create a plot without explicitly defining variable lists. We will also add a title and change the color.
A coin collector initially has 30 coins. After that, for a duration of one month, he finds one coin every day. Show in a line plot how many coins he has each day of that month.

Python3




import pandas as pd
  
#initialize the temperature value at the first day of the month
c = 30
  
# Create a dataframe using the three lists
# the y-axis variable is a list created using
# a for loops, in each iteration, 
# it adds 1 to previous value
# the x-axis variable is a list of values ranging
# from 1 to 31 (31 not included) with a step of 1
df = pd.DataFrame([ c + x for x in range( 0 , 30 )],
                  index = [*range( 1 , 31 , 1 )],
                  columns = [ 'Temperature (C)' ])
  
# use plot() method on the dataframe. 
# No parameters are passed so it uses 
# variables given in the dataframe
df.plot(color='red', title = 'Total Coins per Day')


Output:

Example 4:

In this example, we will plot specific columns of a dataframe. The dataframe consists of three lists, however, we will select two lists only to add to the plot.

Code:

Python3




import pandas as pd
  
# Create a dataframe using three lists
df = pd.DataFrame(
    {'List1': [ 1 , 2 , 3 , 4 , 5 , 6 ], 
     'List2': [ 5 , 10 , 15 , 20 , 25 , 30 ], 
     'List3': [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ]})
  
# use plot() method on the dataframe.
# List3 is in the x-axis and List2 in the y-axis
df.plot( 'List3' , 'List2' )


Output:



Similar Reads

How to Plot a Vertical Line on a Time Series Plot in Pandas
When working with time series data in Pandas, it is often necessary to highlight specific points or events in the data. One effective way to do this is by plotting vertical lines on the time series plot. In this article, we will explore how to plot a vertical line on a time series plot in Pandas, covering the necessary steps, functions, and paramet
3 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Pandas - Plot multiple time series DataFrame into a single plot
In this article, we are going to see how to plot multiple time series Dataframe into single plot. If there are multiple time series in a single DataFrame, you can still use the plot() method to plot a line chart of all the time series. To Plot multiple time series into a single plot first of all we have to ensure that indexes of all the DataFrames
4 min read
Pandas Series dt.freq | Retrieve Frequency of Pandas Time Series
Pandas dt.freq attribute returns the time series frequency applied on the given series object if any, else it returns None. Examples C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_da
2 min read
Pandas Series dt.normalize() | Normalize Time in Pandas Series
The dt.normalize() method converts times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases when the time does not matter. Length is unaltered. The time zones are unaffected. Example: C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'M',
2 min read
Pandas Series dt.weekofyear Method | Get Week of Year in Pandas Series
The dt.weekofyear attribute returns a Series containing the week ordinal of the year in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
Pandas Series dt.minute | Extract Minute from DateTime Series in Pandas
Pandas Series.dt.minute attribute returns a NumPy array containing the minutes of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.dayofweek | Get Day of Week from DateTime Series in Pandas
Pandas dt.dayofweek attribute returns the day of the week from the given DateTime Series Object. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:
2 min read
Pandas Series dt.daysinmonth | Get Number of Days in Month in Pandas Series
The dt.daysinmonth attribute returns the number of days in the month for the given DateTime series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result
2 min read
Creating A Time Series Plot With Seaborn And Pandas
In this article, we will learn how to create A Time Series Plot With Seaborn And Pandas. Let's discuss some concepts : Pandas is an open-source library that's built on top of NumPy library. It's a Python package that gives various data structures and operations for manipulating numerical data and statistics. It's mainly popular for importing and an
4 min read
Convert a series of date strings to a time series in Pandas Dataframe
During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized
3 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
Pandas Scatter Plot – DataFrame.plot.scatter()
A Scatter plot is a type of data visualization technique that shows the relationship between two numerical variables. For plotting to scatter plot using pandas there is DataFrame class and this class has a member called plot. Calling the scatter() method on the plot member draws a plot between two variables or two columns of pandas DataFrame. Synta
2 min read
Python | Pandas Series.plot() method
With the help of Series.plot() method, we can get the plot of pandas series by using Series.plot() method. Syntax : Series.plot() Return : Return the plot of series. Example #1 : In this example we can see that by using Series.plot() method, we are able to get the plot of pandas series. # import Series and matplotlib import pandas as pd import matp
1 min read
How to Plot Multiple Series from a Pandas DataFrame?
In this article, we will discuss how to plot multiple series from a dataframe in pandas. Series is the range of the data that include integer points we cab plot in pandas dataframe by using plot() function Syntax: matplotlib.pyplot(dataframe['column_name']) We can place n number of series and we have to call the show() function to display the plot
2 min read
Python | Pandas series.cumprod() to find Cumulative product of a Series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cumprod() is used to find Cumulative product of a series. In cumulative product, the length of returned series is same as
3 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Pandas Series.astype() to convert Data type of series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas astype() is the one of the most important methods. It is used to change data type of a series. When data frame is made from a csv
2 min read
Python | Pandas Series.cumsum() to find cumulative sum of a Series
Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements. Syntax: Series.cumsum(axis=None, skipna=True) Parameters: axis: 0 or 'index' for row wise operation and 1 or 'columns' for column wise operation skipna: Skip
2 min read
Python | Pandas series.cummax() to find Cumulative maximum of a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative maximum, the length of returned series is same as i
2 min read
Python | Pandas Series.cummin() to find cumulative minimum of a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummin() is used to find Cumulative minimum of a series. In cumulative minimum, the length of returned series is same as i
2 min read
Python | Pandas Series.nonzero() to get Index of all non zero values in a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns i
2 min read
Python | Pandas Series.mad() to calculate Mean Absolute Deviation of a Series
Pandas provide a method to make Calculation of MAD (Mean Absolute Deviation) very easy. MAD is defined as average distance between each value and mean. The formula used to calculate MAD is: Syntax: Series.mad(axis=None, skipna=None, level=None) Parameters: axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation. skipn
2 min read
Convert Series of lists to one Series in Pandas
In this program, we will see how to convert a series of lists of into one series, in other words, we are just merging the different lists into one single list, in Pandas. We will be using the stack() method to perform this task. The line will be Series.apply(Pandas.Series).stack().reset_index(drop = True). The reset_index() method will reset the in
1 min read
Converting Series of lists to one Series in Pandas
Let us see how to convert a Series of lists to a single Series in Pandas. First of all let us create a Series of lists. For this problem we have created a Series of list having 12 elements, each list is of length 3 and there are 4 lists hence total elements are 12. When the Series of list will be converted to one it will have 12 elements. C/C++ Cod
2 min read
Pandas - Get the elements of series that are not present in other series
Sometimes we have two or more series and we have to find all those elements that are present in one series but not in other. We can do this easily, using the Bitwise NOT operator along with the pandas.isin() function. Example 1: Taking two Integer Series C/C++ Code # Importing pandas library import pandas as pd # Creating 2 pandas Series ps1 = pd.S
2 min read
Pandas Series dt.month | Extract Month Part From DateTime Series
The dt.month attribute returns a NumPy array containing the month of the DateTime in the underlying data of the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = id
2 min read
Pandas Series dt.day | Extract Day Part from DateTime Series
Pandas dt.day attribute returns a NumPy array containing the day value of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set th
2 min read
Pandas Series dt.week | Extract Week Number from DateTime Series
Pandas dt.week attribute returns a NumPy array containing the week ordinal of the year in the underlying data of the given DateTime Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.month_name() | Get Month Name From DateTime Series
Pandas dt.month_name() method returns the month names of the DateTimeIndex with specified locale. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result = s
2 min read
three90RightbarBannerImg