Set the candlestick width in Plotly

Viewed 745

In the attached picture, the candlestick's width are different for weekly and daily chart. Does somebody know how to force them the same? Both of them are plotting the same number of candles.

1 Answers
  • candlestick width is defined by number of candlesticks that are in a figure
  • an approach to making them the same width is to plot the same number of candlesticks in various views
  • below shows this technique - tail() dataframe so daily plot has same number of candlesticks as weekly plot
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# generate some data
df = pd.DataFrame({"time": pd.date_range("1-jan-2021", "now", freq="4H")}).pipe(
    lambda d: d.assign(val=np.random.uniform(5, 10, len(d)))
)


def candleFig(df, freq, rows=None, title=None):
    df2 = df.set_index("time").resample(freq).ohlc().droplevel(0, 1)
    if rows:
        df2 = df2.tail(rows)

    return (
        go.Figure(
            data=[go.Candlestick(x=df2.index,
                               open=df2["open"], high=df2["high"],low=df2["low"], close=df2["close"],)]
        ).update_layout(xaxis={"rangeslider": {"visible": False}}, margin={"t": 25, "b": 0},
                        height=150,width=1000, title={"text": title},),
        df2,
    )


fig_w, df_w = candleFig(df, "1W", title="Weekly")
fig_d, df_d = candleFig(df, "1D", rows=len(df_w), title="Daily")

fig_w.show()
fig_d.show()


Related