You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Plotlars TimeSeriesPlot添加次Y轴?

解决Plotlars TimeSeriesPlot添加次Y轴的问题

Plotlars的TimeSeriesPlot构建器的additional_series方法默认会把所有系列绑定到主Y轴,数值范围差异大时就会出现你遇到的平行直线问题。要实现次Y轴,需要绕开这个快捷方法,手动构建每个时间序列的Trace并指定不同Y轴,具体代码如下:

use plotlars::{Plot, Trace, Layout, YAxis};
use polars::prelude::DataFrame;

let df = DataFrame::empty(); // 替换为你的实际数据

// 构建主Y轴的时间序列Trace
let trace1 = Trace::new_time_series(&df, "our_ts", "basis_spread")
    .name("基差");

// 构建次Y轴的时间序列Trace,指定使用y2轴
let trace2 = Trace::new_time_series(&df, "our_ts", "cons_bid")
    .name("cons_bid")
    .yaxis("y2");

// 配置布局,启用次Y轴并设置显示参数
let layout = Layout::new()
    .yaxis(YAxis::new().title("基差"))
    .yaxis2(YAxis::new().title("cons_bid").side("right").overlaying("y"));

// 组装Plot并导出HTML
Plot::new()
    .add_trace(trace1)
    .add_trace(trace2)
    .layout(layout)
    .write_html("/tmp/two_y_axis_plot.html");

关键说明:

  • 放弃TimeSeriesPlot的builder快捷方式,直接使用底层的Plot和Trace构造图表
  • 为次Y轴对应的Trace设置.yaxis("y2"),明确指定它使用第二个Y轴
  • 在Layout中通过.yaxis2()配置次Y轴的标题、显示位置(右侧),并设置overlaying("y")让它和主Y轴重叠显示

内容的提问来源于stack exchange,提问作者skirc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:42:32