Add horizontal lines in Dash for Julia

Viewed 405

I'm trying out Dash from a Julia perspective to create a dashboard. I have a working graph with the following code.

using DataFrames, XLSX, Dates, Dash, DashHtmlComponents, DashCoreComponents, StatsPlots, Indicators

df = DataFrame(XLSX.readtable("file.xlsx", "Price", infer_eltypes=true)...)
    filter!(row -> row.Date >= Date(2018,12,1), df)
    sort!(df)

app  = dash()

app.layout = html_div() do
    html_h1("Price graph"),
    dcc_graph(
        id = "example-graph-1",
        figure = (
            data = [
                (x = df.Date, y = df.Closeprice, type = "line", name = "Closeprice"),
                (x = df.Date, y = sma(df.Closeprice, n=50), type = "line", name = "SMA50"),
                (x = df.Date, y = sma(df.Closeprice, n=200), type = "line", name = "SMA200")
            ],
            layout = (title = "Simple Moving Average", barmode="group")
        )
    )
end

run_server(app, "0.0.0.0", debug=true)

Now I want to create some horizontal lines over this graph at certain points on the y-axies. I have tried looking through documentation but haven't found any good examples on how to create horizontal lines. When I used Statsplotlibrary I could use hline and vline to create different lines, but that doesn't seem to work in Dash. Any guidance would be appreciated.

1 Answers

You could add shapes to the layout.

Simplified reproducible example:

using DataFrames, Dash, DashHtmlComponents, DashCoreComponents

df = DataFrame(Date = [1, 2, 3, 4], Closeprice = [1, 3, 5, 8])

app = dash()

app.layout = html_div() do
    html_h1("Price graph"),
    dcc_graph(
        id = "example-graph-1",
        figure = (
            data = [(x = df.Date, y = df.Closeprice, type = "line", name = "Closeprice")],
            layout = (
                title = "Simple Moving Average",
                barmode = "group",
                shapes = [(
                    type = "line",
                    x0 = 0,
                    x1 = 1,
                    xref = "paper",
                    y0 = 4,
                    y1 = 4,
                    yref = "y",
                    line = (color = "Red", width = 2)
                )],
            ),
        ),
    )
end

run_server(app, "0.0.0.0", debug = true)

Result:

hline

xref = "paper" is used so the line spans the entire graph.

By default, text annotations have xref and yref set to "x" and "y", respectively, meaning that their x/y coordinates are with respect to the axes of the plot. This means that panning the plot will cause the annotations to move. Setting xref and/or yref to "paper" will cause the x and y attributes to be interpreted in paper coordinates.

https://plotly.com/python/text-and-annotations/

The above quote is from the Python documentation, but the same applies here.

Related