Plotly: How to style a plotly figure so that it doesn't display gaps for missing dates?

后端 未结 2 2009
半阙折子戏
半阙折子戏 2020-12-18 13:18

I have a plotly graph of the EUR/JPY exchange rate across a few months in 15 minute time intervals, so as a result, there is no data from friday evenings to sunday evenings.

相关标签:
2条回答
  • 2020-12-18 13:58

    Even if some dates are missing in your dataset, plotly interprets your dates as date values, and shows even missing dates on your timeline. One solution is to grab the first and last dates, build a complete timeline, find out which dates are missing in your original dataset, and include those dates in:

    fig.update_xaxes(rangebreaks=[dict(values=dt_breaks)])
    

    This will turn this figure:

    Into this:

    Complete code:

    import plotly.graph_objects as go
    from datetime import datetime
    import pandas as pd
    import numpy as np
    
    # sample data
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
    
    # remove some dates to build a similar case as in the question
    df = df.drop(df.index[75:110])
    df = df.drop(df.index[210:250])
    df = df.drop(df.index[460:480])
    
    # build complete timepline from start date to end date
    dt_all = pd.date_range(start=df['Date'].iloc[0],end=df['Date'].iloc[-1])
    
    # retrieve the dates that ARE in the original datset
    dt_obs = [d.strftime("%Y-%m-%d") for d in pd.to_datetime(df['Date'])]
    
    # define dates with missing values
    dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d").tolist() if not d in dt_obs]
    
    # make fiuge
    fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                    open=df['AAPL.Open'], high=df['AAPL.High'],
                    low=df['AAPL.Low'], close=df['AAPL.Close'])
                          ])
    
    # hide dates with no values
    fig.update_xaxes(rangebreaks=[dict(values=dt_breaks)])
    
    fig.update_layout(yaxis_title='AAPL Stock')
    
    fig.show()
    
    0 讨论(0)
  • 2020-12-18 14:18

    thanks for the amazing sample! works on daily data but with intraday / 5min data rangebreaks only leave one day on chart

        # build complete timepline 
        dt_all = pd.date_range(start=df.index[0],end=df.index[-1], freq="5T")
        # retrieve the dates that ARE in the original datset
        dt_obs = [d.strftime("%Y-%m-%d %H:%M:%S") for d in pd.to_datetime(df.index, format="%Y-%m-%d %H:%M:%S")]
        # define dates with missing values
        dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d %H:%M:%S").tolist() if not d in dt_obs]
    
    0 讨论(0)
提交回复
热议问题