How to Plot a Vertical Line on a Time Series Plot in Pandas

Last Updated : 05 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 parameters to achieve this.

Plotting Time Series Plot in Pandas

Time series plots display data points indexed in time order. They are particularly useful for analyzing trends, seasonal patterns, and anomalies in data over time. Vertical lines on these plots can denote significant events, such as changes in policy, milestones, or anomalies.

Creating a Time Series Plot with Pandas:

Pandas provides a powerful and easy-to-use interface for time series data manipulation and visualization. Let's start by creating a simple time series plot.

Python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Creating sample data
dates = pd.date_range(start='2023-01-01', periods=100, freq='D')
data = np.random.randn(100).cumsum()
df = pd.DataFrame(data, index=dates, columns=['Value'])
# Plotting the time series
df.plot()
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot')
plt.show()

Output:

download---2024-07-05T133955925
Time Series Plot with Pandas

Adding Vertical Lines to the Time Series Plot

There are several ways to add vertical lines to a time series plot in Pandas. We will explore three methods: using axvlinevlines, and annotate functions from Matplotlib.

Method 1: Using axvline

The axvline function in Matplotlib adds a vertical line across the entire plot. This method allows you to specify the x-coordinate (date) where the line should be drawn.

Python
ax = df.plot()
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot with Vertical Line')

# Add a vertical line at a specific date
plt.axvline(x=pd.to_datetime('2023-02-15'), color='r', linestyle='--', label='Important Date')
plt.legend()
plt.show()

Output:

download---2024-07-05T133816343
Using axvline

Method 2: Using vlines

The vlines function allows for more customization, such as specifying the range of the vertical line.

Python
ax = df.plot()
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot with Vertical Line')

# Add a vertical line at a specific date with a specified range
plt.vlines(x=pd.to_datetime('2023-02-15'), ymin=df['Value'].min(), ymax=df['Value'].max(), color='g', linestyle='-', label='Event')
plt.legend()
plt.show()

Output:

download---2024-07-05T133521004
Using vlines

Method 3: Using annotate

The annotate function can be used to add text annotations along with vertical lines.

Python
# Plot the time series data
ax = df.plot()
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot with Annotation')

# Add a vertical line and annotation
plt.axvline(x=pd.to_datetime('2023-02-15'), color='b', linestyle=':', label='Annotation Date')
plt.annotate('Event', xy=(pd.to_datetime('2023-02-15'), df['Value'].mean()), xytext=(pd.to_datetime('2023-02-15'), df['Value'].max()),
             arrowprops=dict(facecolor='black', shrink=0.05))
plt.legend()
plt.show()

Output:

download---2024-07-05T133646964
Using annotate

Plotting Multiple Vertical Lines with Time Series Plot

If you need to highlight multiple events, you can add multiple vertical lines by calling axvline for each event.

Python
# Specifying multiple dates for the vertical lines
event_dates = ['2023-02-01', '2023-02-15', '2023-03-01']
ax = df.plot()

# Adding multiple vertical lines
for event_date in event_dates:
    plt.axvline(x=event_date, color='green', linestyle='--', linewidth=1)

# Adding labels and title
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot with Multiple Vertical Lines')
plt.show()

Output:

download---2024-07-05T134333044
Multiple Vertical Lines with Time Series Plot

Conclusion

Plotting vertical lines on a time series plot in Pandas is a straightforward process that enhances the visualization by highlighting significant events or time points. By using Matplotlib's axvline method, you can easily add and customize these lines to provide better insights into your data.


Similar Reads

Time Series Plot or Line plot with Pandas
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 cl
6 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
Creating Vertical Line in ggplot with Time Series Data Using R
In time series analysis, it is often useful to highlight key events or thresholds using vertical lines on plots. In R, ggplot2 makes it easy to add vertical lines to your plots using the geom_vline() function. In this article, we will explore how to add vertical lines to time series data plots using ggplot2. In this article, we will cover how to cr
4 min read
Add Moving Average Plot to Time Series Plot in R
In time series analysis, a moving average is a widely used technique to smooth out short-term fluctuations and highlight longer-term trends or cycles. R provides several ways to compute and visualize moving averages alongside time series data. This article will guide you through the process of adding a moving average plot to a time series plot in R
3 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
How to Plot Multiple Series/Lines in a Time Series Using Plotly in R?
Plotly is a powerful and flexible graphing library that enables the creation of interactive plots in R. It is especially useful for visualizing time series data with multiple lines or series. In this article, we will cover how to plot multiple time series in a single plot using Plotly in R. Multiple Time SeriesMultiple time series involve more than
5 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
Plot Logistic Regression Line Over Heat Plot in R
Plotting a logistic regression line over a heat plot can be a powerful way to visualize the relationship between predictor variables and a binary outcome. This article will guide you through the steps to create such a visualization in R. What is a Logistic Regression Line?In logistic regression, the logistic regression line is the decision boundary
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
three90RightbarBannerImg