How to Create a Line Plot with a Datetime Index in Python?

Estimated read time 2 min read

To create a line plot with a datetime index in Python, you can use the matplotlib library in combination with the pandas library, which provides tools for working with time series data. Here’s how you can create a line plot:

import pandas as pd
import matplotlib.pyplot as plt

# Define your datetime index and data
date_rng = pd.date_range(start='1/1/2022', end='1/10/2022', freq='H')
data = pd.Series(range(len(date_rng)), index=date_rng)

# Create a figure and axis object
fig, ax = plt.subplots()

# Plot the data as a line
ax.plot(data.index, data)

# Add labels and title
ax.set_xlabel('Date')
ax.set_ylabel('Value')
ax.set_title('Line Plot with Datetime Index')

# Show the plot
plt.show()

In the code above, we first import the pandas and matplotlib.pyplot modules as pd and plt, respectively. We then define our datetime index using the date_range() function of pandas, which creates a range of datetime values from January 1, 2022 to January 10, 2022 with an hourly frequency. We also define our data as a pd.Series object with the same length as the datetime index.

Next, we create a figure and axis object using the subplots() function, as before.

We then use the plot() method of the axis object to plot the data as a line. However, this time we need to specify the x-axis values explicitly as the datetime index of the data.

Finally, we use the set_xlabel(), set_ylabel(), and set_title() methods of the axis object to add labels and a title to the plot, as before. We then call plt.show() to display the plot.

This will create a line plot with a datetime index, with the x-axis representing the dates and times and the y-axis representing the values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply