如何修复R中plot_ly subplot输出的双Y轴子图混乱问题?
问题根源
subplot默认共享X/Y轴,会覆盖你单独为每个子图设置的轴范围,导致数据被压缩- 双Y轴子图合并时,轴索引会被自动重命名,原有
overlaying = "y"的绑定关系失效,导致柱状图丢失 subplot默认不会保留子图的独立标题,子图原有title配置会被全局设置覆盖- 你在
subplot调用后全局设置的xaxis/yaxis只会作用到第一个子图,同时会覆盖其原有配置 - 你原有代码里所有
yaxis2的配置中存在拼写错误:scaleacnchor应为scaleanchor,会导致双Y轴缩放规则失效
修复方案
先把所有子图里的scaleacnchor修正为scaleanchor,再替换原有subplot调用代码即可:
Plot <- subplot(plot1, plot2, plot3, plot4, nrows = 2, shareX = FALSE, # 不共享X轴,保留每个子图的独立范围 shareY = FALSE, # 不共享Y轴,保留每个子图的独立范围 titleX = TRUE, # 保留子图的X轴标题 titleY = TRUE, # 保留子图的Y轴标题 margin = 0.08) %>% # 子图之间预留边距,避免标签、标题遮挡 layout( plot_bgcolor = '#e5ecf6', # 用annotations添加四个子图的独立标题 annotations = list( list(text = "# Actuals for State 23, Crop 41.", x = 0.22, y = 1.0, xref = "paper", yref = "paper", showarrow = F, font = list(size = 14)), list(text = "# bias for State 23, Crop 41.", x = 0.78, y = 1.0, xref = "paper", yref = "paper", showarrow = F, font = list(size = 14)), list(text = "# cat for State 23, Crop 41.", x = 0.22, y = 0.42, xref = "paper", yref = "paper", showarrow = F, font = list(size = 14)), list(text = "# cvglvl for State 23, Crop 41.", x = 0.78, y = 0.42, xref = "paper", yref = "paper", showarrow = F, font = list(size = 14)) ) ) htmlwidgets::saveWidget(Plot, paste0('Number of actuals-cvglvl for State 23, Crop 41.html'))
如果修改后仍有双Y轴元素丢失,升级plotly到4.10.0及以上版本即可,官方在该版本修复了subplot对多Y轴绑定的已知bug。
内容的提问来源于stack exchange,提问作者PDiddyA
相关产品推荐
相关产品推荐

