如何不调整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)))
关键说明
- Balance数值映射:通过
Balance / max(Balance) * max(c(Principal, Interest))将Balance的量级缩放到和Principal/Interest一致,实现折线叠加,但原始数据并未修改。 - 双y轴转换:右侧y轴通过反向转换公式,把缩放后的数值还原为Balance的原始值,保证轴刻度显示真实剩余本金。
- ggplotly tooltip处理:通过
style函数判断折线类别,当为Balance时直接调用原始Balance字段展示,避免显示缩放后的数值。
内容的提问来源于stack exchange,提问作者Seoyoung Park
相关产品推荐
相关产品推荐

