0

Hi i tried to shade the area between two point in time. i.e. 13:00 to 14:00 but keep getting a. ConversionError: Failed to convert value(s) to axis units: ['13,00', '14,00']

for date in dates:
data = df[df['TradeTimeUtc'].dt.date == date]


fig, ax1 = plt.subplots()

# plot spread on primary axis
ax1.plot(data['TradeTimeUtc'], data['spread'], color='blue')
ax1.set_xlabel('TradeTimeUtc')
ax1.set_ylabel('spread', color='blue')
ax1.tick_params('y', colors='blue')

# add a vertical shaded region to highlight the time between 13:00 to 14:00 and this is where the problem is 
ax1.axvspan("12:00","13:00", alpha=0.2, color='gray')


# create a secondary axis for Volume
ax2 = ax1.twinx()

# plot Volume on secondary axis as a bar chart
ax2.bar(data['TradeTimeUtc'], data['acc_vol'], width = 0.0003, color='red', alpha=0.1)
ax2.set_ylabel('Volume', color='red')
ax2.tick_params('y', colors='red')

# set plot title
ax1.set_title(f'Spread and Volume on {date}')

# adjust layout
fig.tight_layout()

# show plot
plt.show()

for some reason it is not picking up the time i wanted to shade, any advice welcome, thanks

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
kit12_31
  • 89
  • 2
  • 8

1 Answers1

-1

Since we cannot run your code without data, this is only guess work:

Your x-axis seems to be strings, so this might already do the trick:

ax1.axvspan("12,00","13,00", alpha=0.2, color='gray')

However, usually you want to have proper datetime objects as x values. This is an minimal working example. However, your case might be different.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime

y_values = np.random.rand(20)
x_values = pd.date_range("2023-01-01T00:00", "2023-01-01T20:00", 20)


# get axis object
ax = plt.gca()
plt.plot(x_values, y_values)
ax.axvspan(
    datetime(2023, 1, 1, 3),
    datetime(2023, 1, 1, 5),
    alpha=0.2,
    color='gray'
)

plt.savefig("out.jpg")

enter image description here

Klops
  • 951
  • 6
  • 18