The Dan
The Dan

Reputation: 1680

Plotly: How to implement Date-time range in X axis on a randomly generated Time-Series

I am generating a random walk time series which starts in day 1 and finishes in day "l",

I would like to represent dates on my x_axis, where the series starts in an initial day established by input and ending the day "l"

This code generates the time series:

import plotly.graph_objects as go
import numpy as np

l = 360 # Number of days to Study
time_step = 1
# initial_y = int(input('Enter initial value: '))
x_steps = np.random.choice([0, 0], size=l) + time_step  # l steps
y_steps = np.random.choice([-1, 1], size=l) + 0.2 * np.random.randn(l) # l steps
x_position = np.cumsum(x_steps) # integrate the position by summing steps values
y_position = np.cumsum(y_steps) # integrate the position by summing steps values

fig = go.Figure(data=go.Scatter(
    x=x_position,
    xcalendar='gregorian', 
    # range_x=['2015-12-01', '2016-01-15'],
    y=y_position + 1500,
    mode='lines+markers',
    name='Random Walk',
    marker=dict(
        color=np.arange(l),
        size=8,
        colorscale='Greens',
        showscale=False
    )
))

fig.show()

Upvotes: 0

Views: 2627

Answers (1)

rpanai
rpanai

Reputation: 13437

You can add to your example this:

initial_date = '2015-12-01'

df = pd.DataFrame({"x":x_position,
                   "y":y_position})

df["date"] = pd.date_range(start=initial_date, periods=l)

fig = go.Figure(data=go.Scatter(
    x=df["date"],
    xcalendar='gregorian', 
    # range_x=['2015-12-01', '2016-01-15'],
    y=df["y"] + 1500,
    mode='lines+markers',
    name='Random Walk',
    marker=dict(
        color=np.arange(l),
        size=8,
        colorscale='Greens',
        showscale=False
    )
))

fig.show()

enter image description here

Upvotes: 2

Related Questions