Adding vertical lines on line graph distorting scale

Viewed 80

I have a line graph with datetime in the X axis that I modify the format to show HH:MM:SS

fig.update_xaxes(title_font=dict(size=12), tickformat='%X')

Before vertical lines are added, the scale is perfect: enter image description here

Example 1: vline adding the value: 1970-01-01T00:00:00.000000000:

enter image description here

Example 2 vline adding the value: 1970-01-01T00:01:34.000000000

enter image description here

My vertical line code is:

for loop...
if time in df['ColA'].values:
fig.add_vline(x=df[df['ColA'] == time)]['ColB'].values[0])
 

ColA and variable time (iterator in the loop) is of type string and has values as such. Values are coming from selected rows indices from a callback

0:00:00
0:01:34

ColB is a datetime64[ns] type:

1970-01-01 00:00:00
1970-01-01 00:01:34

And my graph is a px.line graph with facetted rows and im using ColB on the X axis.

Why is the scale completely changing if the vline value x is of the same type and within the same range?

1 Answers
  • it all comes down to type coercing
  • df["ColA"].values returns an array of datetime64[ns]
  • inspect fig.data[0].x and it returns an array of datetime.datetime
  • make them consistent with pd.Timestamp(time).to_pydatetime()
  • have simulated some data, no faceting as you have not included any details of this in your question
ROWS = 20
df = pd.DataFrame({"ColA":pd.date_range("1-jan-1970", freq="4H", periods=ROWS), "ColB":np.random.uniform(1,30, ROWS)})

fig = px.line(df, x="ColA", y="ColB")
fig.update_xaxes(title_font=dict(size=12), tickformat='%X')

for time in df["ColA"].values:
    if time in df['ColA'].values:
        fig.add_vline(x=pd.Timestamp(time).to_pydatetime())

fig

enter image description here

Related