Plotly:如何绘制“2 点”之间的水平线,其中 x 轴上的点是月份

Plotly: How to plot Horizontal line Between "2 Points" where points on x axis are Months

有没有办法控制plotly中横线和竖线的起点和终点?

import plotly.graph_objects as go
        
fig = go.Figure(data=go.Scatter())
fig.add_vline(x=1, line_width=2, line_dash="dash", line_color="green")
fig.add_hline(y=2, line_width=2, line_dash="dash", line_color="red")
fig.show()

上面的代码将在整个屏幕上绘制线条

我想做这样的事情:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize = (10,7))

ax.hlines(y=2, xmin='July', xmax='Aug', linewidth=2, color='red', linestyles = 'dotted')
ax.axvline(x = 1,color = 'green', linestyle = 'dotted', linewidth = 2)

documentation 开始,add_vline 将跨越绘图的整个 y 轴,add_hline 将跨越绘图的整个 x 轴。

您可以改为对 Plotly Shapes 中的图形使用 add_shape 方法,并通过使用参数 x0、[=15= 指定起点和终点坐标来添加线段],y0,y1.

编辑:如果您的 x 轴上有日期时间,您可以将日期时间传递给 x 坐标参数

import plotly.express as px
import pandas as pd

df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG")

vertical_date_time = pd.to_datetime("2018-07-01")
horizontal_date_time_start = pd.to_datetime("2018-04-01")
horizontal_date_time_end = pd.to_datetime("2018-10-01")
fig.add_shape(type="line", x0=vertical_date_time, y0=0.9, x1=vertical_date_time, y1=1.2, line_width=2, line_dash="dash", line_color="green")
fig.add_shape(type="line", x0=horizontal_date_time_start, y0=1.05, x1=horizontal_date_time_end, y1=1.05, line_width=2, line_dash="dash", line_color="red")

fig.show()