如何在Julia版Dash的图表中添加指定y轴位置的水平辅助线
你在Julia Dash中添加水平辅助线可以直接通过Plotly原生的shapes配置项实现,无需调用StatsPlots的相关方法,具体修改方式如下:
实现逻辑
- 水平辅助线属于图表布局的静态形状,需要添加在
figure的layout字段下的shapes数组中 - 每条水平辅助线对应
shapes数组中的一个配置项,固定x轴范围为你数据的时间区间,y轴固定为你需要的参考值即可
修改后完整示例代码
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) # 提前计算时间范围给辅助线用 date_min, date_max = extrema(df.Date) 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", # 新增shapes配置添加水平辅助线 shapes = [ # 第一条水平辅助线,示例y值为150 ( type = "line", x0 = date_min, x1 = date_max, y0 = 150, y1 = 150, line = ( color = "gray", width = 2, dash = "dash" # 可选值:solid、dot、dash ) ), # 第二条水平辅助线,示例y值为300 ( type = "line", x0 = date_min, x1 = date_max, y0 = 300, y1 = 300, line = ( color = "red", width = 1.5, dash = "dot" ) ) ] ) ) ) end run_server(app, "0.0.0.0", debug=true)
如果需要添加更多水平辅助线,只需在shapes数组中按上述格式新增对应配置即可,你可以根据需求调整线条的颜色、粗细、样式。如果要添加垂直辅助线,反过来固定y轴范围、x轴设置为指定日期值即可。
内容的提问来源于stack exchange,提问作者hbrovell
相关产品推荐
相关产品推荐

