plot a vertical line if the date is a weekend in matplotlbi in python

To plot a vertical line in matplotlib if a date is a weekend, you can use the axvline function of matplotlib and the isoweekday method of datetime objects in Python.

Here's an example code snippet that demonstrates how to achieve this:

main.py
import matplotlib.pyplot as plt
from datetime import datetime

# Generate a list of dates
dates = ['2021-10-01', '2021-10-02', '2021-10-03', '2021-10-04', '2021-10-05', '2021-10-06']

# Convert string dates to datetime objects
dates = [datetime.strptime(date, '%Y-%m-%d') for date in dates]

# Plot the dates on x-axis
plt.plot(dates, [0]*len(dates))

# Iterate over the dates
for date in dates:
    # Check if the date is a weekend (Saturday or Sunday)
    if date.isoweekday() in [6, 7]:
        # Plot a vertical line at x-coordinate of the date
        plt.axvline(x=date, color='r', linestyle='--')

# Display the plot
plt.show()
635 chars
22 lines

In this example, we first convert the string dates to datetime objects using the strptime method. Then, we plot the dates on the x-axis using plt.plot. Finally, we iterate over the dates, check if each date is a weekend using the isoweekday method, and plot a vertical line using plt.axvline if the date is a weekend.

This will result in a plot with vertical lines at the x-coordinates of the weekend dates.

related categories

gistlibby LogSnag