如何将自定义Histogram嵌入Table.cell并置于图表底部?
解决Pine Script中直方图嵌入表格的问题
Pine Script 5中不支持将plot()生成的直方图直接嵌入到表格单元格内——表格(table)仅支持文本、基础图形(矩形、线条等)元素,无法直接插入由plot()创建的独立绘图对象。以下是两种可行的替代方案:
方案一:手动在表格单元格内绘制迷你直方图
通过计算数据归一化值,使用表格的形状绘制功能模拟直方图柱子,实现嵌入效果:
//@version=5 indicator("Table with Mini Histogram", overlay=true) // 替换为你的MC数据 MC = ta.close - ta.open // 创建底部表格 var table_hma = table.new(position.bottom_center, 10, 6, border_width=2, border_color=color.gray, frame_color=color.gray, frame_width=2) table.cell(table_hma, 0, 0, text = "SMA", bgcolor=color.black, text_color=color.white, text_size=size.small) // 准备最近20条直方图数据 hist_length = 20 hist_data = array.new_float(hist_length) for i = 0 to hist_length - 1 array.set(hist_data, i, MC[i]) // 计算数据范围用于归一化(适配单元格高度) min_val = array.min(hist_data) max_val = array.max(hist_data) val_range = max_val - min_val val_range := val_range == 0 ? 1 : val_range // 避免除以0 // 指定直方图所在单元格(第0列第1行) cell_col = 0 cell_row = 1 table.cell(table_hma, cell_col, cell_row, bgcolor=color.black) // 获取单元格坐标(仅在最后一根K线计算一次) var cell_info = table.get_cell_position(table_hma, cell_col, cell_row) if barstate.islast cell_info := table.get_cell_position(table_hma, cell_col, cell_row) // 计算单根柱子宽度(留间距) bar_width = (cell_info.width / hist_length) * 0.8 // 遍历绘制每根柱子 for i = 0 to hist_length - 1 val = array.get(hist_data, i) // 归一化值到单元格高度范围 norm_val = (val - min_val) / val_range bar_height = norm_val * cell_info.height // 计算柱子位置(区分正负值) bar_x = cell_info.x + (i * bar_width) + (bar_width * 0.1) bar_y = val >= 0 ? cell_info.y + cell_info.height - bar_height : cell_info.y + cell_info.height // 在单元格内绘制矩形柱子 table.cell_set_shape(table_hma, cell_col, cell_row, shape.rect, x=bar_x, y=bar_y, width=bar_width * 0.8, height=math.abs(bar_height), color=val >= 0 ? color.green : color.red, border_color=color.gray)
方案二:调整原生直方图位置与表格配合
如果不需要严格嵌入表格,可将直方图放在独立副图并调整高度,同时在主图底部放置表格:
//@version=5 indicator("Histogram + Bottom Table", overlay=true) // 替换为你的MC数据 MC = ta.close - ta.open // 将直方图放在副图(数据窗口),保持原生样式 plot(MC, color=color.bar, linewidth=1, style=plot.style_histogram, title='1', display=display.data_window) // 在主图底部创建表格 var table_hma = table.new(position.bottom_center, 10, 6, border_width=2, border_color=color.gray, frame_color=color.gray, frame_width=2) table.cell(table_hma, 0, 0, text = "SMA", bgcolor=color.black, text_color=color.white, text_size=size.small)
方案对比
- 方案一:完全嵌入表格,样式高度可控,但需要手动处理数据归一化和绘制逻辑,适合展示小范围的迷你直方图。
- 方案二:使用原生
plot()功能,实现简单,但直方图位于副图,并非真正嵌入表格。
内容的提问来源于stack exchange,提问作者chprot
相关产品推荐
相关产品推荐

