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

R语言如何调整Plotly图表次Y轴标题与刻度值的显示位置

核心问题原因

  • 代码中position = 2参数放置层级错误,不属于yaxis2的同级配置,属于无效参数,干扰了布局计算
  • 绘图区域默认右边距过小,没有给右侧次Y轴预留足够的显示空间

修正后完整代码

plotly::plot_ly(data = india, x = ~ Date, y = ~ Daily.Confirmed,
                type = "scatter", mode = "fill",fill = "tozeroy", name = "Confirmed Cases",
                fillcolor ="#ff5c67",  line = list(color = "#94010b", width = 3))%>%
  plotly::add_trace(x = ~ Date, y = ~ Daily.Deceased, marker = list( 
                     color = "#757f80"), type = "bar", name = "Deaths",
                   yaxis = "y2")%>%
  plotly::layout(title = "",plot_bgcolor='#e5ecf6',
                 # 新增margin配置,r对应右边距,可根据显示效果调整数值
                 margin = list(r = 60),
                 legend = list(x = 0.03, y = 0.95),
                 yaxis = list(title = "Number of Cases",zerolinecolor = '#ffff',
                              zerolinewidth = 2,
                              gridcolor = 'ffff'),
                 xaxis = list(title = "Confirmed Cases Trend",zerolinecolor = '#ffff',
                              zerolinewidth = 2,
                              gridcolor = 'ffff'),
                 yaxis2 = list(title = "Number of Deaths", overlaying = "y",
                               side = "right", range = c(0, 20000), 
                               gridcolor = "#e5ecf6"),
                 hovermode = "compare")

可选优化配置

如果调整边距后还是觉得显示拥挤,可以在yaxis2的配置中添加automargin = TRUE开启刻度自适应,或者手动调整标题、刻度的字号:

yaxis2 = list(title = "Number of Deaths", overlaying = "y",
              side = "right", range = c(0, 20000), 
              gridcolor = "#e5ecf6",
              automargin = TRUE, # 自适应边距
              titlefont = list(size = 12), # 标题字号
              tickfont = list(size = 10)) # 刻度字号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:18:01