matplotlib 绘制两个时间点之间的阴影区域[一式两份]

vsmadaxz  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(132)

此问题在此处已有答案

Using axvspan for date ranges(2个答案)
1小时前关闭。
嗨,我试图在两个时间点之间的区域进行着色。即13:00至14:00,但不断得到一个. ConversionError:无法将值转换为轴单位:【十三时,十四时】

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()

由于某种原因,它没有拿起我想遮阳的时间,任何建议欢迎,谢谢

siv3szwd

siv3szwd1#

因为没有数据我们无法运行代码,所以这只是猜测:
你的x轴看起来是字符串,所以这可能已经达到了目的:

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

然而,通常你希望有合适的datetime对象作为x值。这是一个最小的工作示例。然而,你的情况可能不同。

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")

相关问题