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

如何在R中调整Plotly仪表盘刻度:隐藏刻度并迁移最值标签至底部

Plotly 仪表盘刻度问题修复及 ggplot2 替代实现

一、Plotly 解决方案

针对无法隐藏中间刻度、无法将最小/最大刻度放在图表下方、调整参数导致标题布局混乱的问题,修改代码如下:

plot1 <- plotly::plot_ly(
  type = "indicator",
  mode = "gauge+number",
  value = 42.2,
  title = list(
    text = "Jump Height", 
    font = list(size = 30, color = "white"),
    y = 0.9  # 调整标题垂直位置,避免和仪表盘重叠
  ),
  gauge = list(
    axis = list(
      range = list(0, 50),
      tickmode = "array",          # 指定自定义刻度值
      tickvals = c(0, 50),        # 仅保留最小、最大刻度
      ticktext = c("0", "50"),    # 对应刻度文本
      tickfont = list(color = "white"),
      tickposition = "outside",   # 将刻度标签放在仪表盘外侧
      ticks = "",                 # 隐藏刻度线
      tickcolor = "transparent"   # 确保刻度线完全不可见
    ),
    bar = list(color = "royalblue", thickness = 1),
    bgcolor = "white",
    borderwidth = 0
  )
) %>% plotly::layout(
  margin = list(t=50, r=20, b=40, l=20),  # 增加底部边距,容纳下方刻度
  paper_bgcolor = "black",
  font = list(color = "white", family = "Arial")
)

plot1

关键调整点:

  • 用tickmode = "array"配合tickvals精准控制显示的刻度,直接隐藏中间刻度
  • tickposition = "outside"将刻度标签移到仪表盘外侧,结合底部边距调整位置
  • 调整标题的y参数,避免布局挤压导致混乱
  • 把tickcolor设为透明,彻底消除刻度线,无需依赖背景色隐藏

二、ggplot2 替代实现

如果需要用 ggplot2 实现类似样式,代码如下(依赖ggplot2和dplyr):

library(ggplot2)
library(dplyr)

# 准备数据
gauge_data <- tibble(
  value = 42.2,
  max_value = 50,
  title = "Jump Height"
)

# 转换角度为弧度(仪表盘采用-120°到120°的半圆范围)
start_angle <- -120 * pi / 180
end_angle <- 120 * pi / 180
value_angle <- start_angle + (end_angle - start_angle) * (gauge_data$value / gauge_data$max_value)

ggplot(gauge_data, aes(x = 0, y = 0)) +
  # 绘制背景刻度盘
  geom_arc(aes(x0 = 0, y0 = 0, r = 1, start = start_angle, end = end_angle),
           color = "white", size = 10, lineend = "round") +
  # 绘制进度条
  geom_arc(aes(x0 = 0, y0 = 0, r = 1, start = start_angle, end = value_angle),
           color = "royalblue", size = 10, lineend = "round") +
  # 显示核心数值
  geom_text(aes(label = sprintf("%.1f", value)), 
            color = "white", size = 12, fontface = "bold") +
  # 显示标题
  geom_text(aes(label = title), y = 1.5, 
            color = "white", size = 10, fontface = "bold") +
  # 显示最小/最大刻度标签
  geom_text(aes(x = cos(start_angle) * 1.2, y = sin(start_angle) * 1.2, label = "0"),
            color = "white", size = 5) +
  geom_text(aes(x = cos(end_angle) * 1.2, y = sin(end_angle) * 1.2, label = "50"),
            color = "white", size = 5) +
  # 布局调整
  coord_fixed() +
  theme_void() +
  theme(plot.background = element_rect(fill = "black", color = NA))

说明:

  • 通过geom_arc绘制仪表盘的背景和进度条,角度范围模拟Plotly的半圆样式
  • 用三角函数计算刻度标签的位置,确保放在仪表盘外侧下方
  • 用theme_void()清除默认坐标轴,设置黑色背景匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:52:50