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

如何不调整y值实现双Y轴叠加并保留ggplotly原始数据值

解决贷款摊销折线图双y轴叠加且ggplotly显示原始值的方法

核心思路是利用双y轴实现不同量级数据的叠加展示,无需修改原始Balance数值,同时让ggplotly能正确显示原始数据。

代码示例

首先模拟一个贷款摊销数据集(你可以替换成自己的annual_amortization):

# 模拟贷款摊销数据集
annual_amortization <- data.frame(
  Year = 1:10,
  Principal = c(8000, 8500, 9000, 9500, 10000, 10500, 11000, 11500, 12000, 12500),
  Interest = c(5000, 4500, 4000, 3500, 3000, 2500, 2000, 1500, 1000, 500),
  Balance = c(92000, 83500, 74500, 65000, 55000, 44500, 33500, 22000, 10000, 0)
)

接下来绘制带双y轴的ggplot并转换为ggplotly:

library(ggplot2)
library(plotly)

# 构建基础双y轴ggplot
p <- ggplot(annual_amortization, aes(x = Year)) +
  # 绘制Principal和Interest,对应左侧y轴
  geom_line(aes(y = Principal, color = "Principal"), linewidth = 1) +
  geom_line(aes(y = Interest, color = "Interest"), linewidth = 1) +
  # 将Balance映射到左侧y轴的数值范围(不修改原始数据)
  geom_line(aes(y = Balance / max(Balance) * max(c(Principal, Interest)), color = "Balance"), linewidth = 1) +
  # 设置双y轴:左侧显示Principal/Interest,右侧显示原始Balance
  scale_y_continuous(
    name = "Principal / Interest",
    sec.axis = sec_axis(
      trans = ~ . * max(annual_amortization$Balance) / max(c(annual_amortization$Principal, annual_amortization$Interest)),
      name = "Remaining Balance"
    )
  ) +
  scale_color_manual(values = c("Principal" = "blue", "Interest" = "red", "Balance" = "green")) +
  labs(title = "Loan Annual Amortization", x = "Year", color = "Category") +
  theme_minimal()

# 转换为ggplotly,确保tooltip显示原始数值
ggplotly(p, tooltip = c("x", "color")) %>%
  style(text = ~ifelse(color == "Balance", 
                       paste0("Balance: ", Balance),
                       paste0(color, ": ", y)))

关键说明

  1. Balance数值映射:通过Balance / max(Balance) * max(c(Principal, Interest))将Balance的量级缩放到和Principal/Interest一致,实现折线叠加,但原始数据并未修改。
  2. 双y轴转换:右侧y轴通过反向转换公式,把缩放后的数值还原为Balance的原始值,保证轴刻度显示真实剩余本金。
  3. ggplotly tooltip处理:通过style函数判断折线类别,当为Balance时直接调用原始Balance字段展示,避免显示缩放后的数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:42:50