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

R语言plotly雷达图径向轴标签自定义:添加百分号、替换单位M为Mio

Plotly雷达图径向轴标签修改方案

核心配置说明

scatterpolar类型图表的径向轴配置不在trace参数中,而是通过layout()函数下的polar.radialaxis属性修改,这也是查阅官方文档时容易找错的位置。

需求1:径向轴添加百分号后缀

直接在原有绘图代码末尾追加layout配置即可,核心配置为ticksuffix = "%",可搭配tickformat参数控制小数显示规则。
完整示例代码:

library(tidyverse)
library(plotly)
# 测试数据
d <- structure(
  list(
    Region = c("A", "A", "A", "B", "B", "B", "C",
               "C", "C"),
    Bezeichnung = c(
      "Agriculture",
      "Industry",
      "Services",
      "Agriculture",
      "Industry",
      "Services",
      "Agriculture",
      "Industry",
      "Services"
    ),
    Diff = c(9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L),
    Wachstum = c(5,
                 3, 3, 5, 4, 4, 3, 3, 4),
    Wert = c(
      1322956.10582307,
      1362979.06356215,
      352138.918156773,
      340230.355633795,
      83354.3466503918,
      1476435.89480847,
      1321136.99315399,
      388579.265012443,
      715511.4116247
    )
  ),
  class = c("tbl_df",
            "tbl", "data.frame"),
  row.names = c(NA,-9L)
)
regions <- c("A", "B", "C")

# 绘图代码
fig <- plot_ly(
  type = "scatterpolar",
  fill = "toself",
  mode = "lines+markers"
)
for (i in 1:3) {
  d1 <- d %>% filter(Region %in% regions[i])
  fig <- fig %>%
    add_trace(
      r = d1 %>% slice(1:3, 1) %>% pull(Wachstum),
      theta = d1 %>% slice(1:3, 1) %>% pull(Bezeichnung),
      name = d1 %>% slice(1) %>% pull(Region),
      hovertemplate = paste0(
        "%{fullData.name}<br>",
        "%{theta}<br>",
        "Wachstum: %{r:.3} %",
        "<extra></extra>"
      )
    )
}
# 新增径向轴配置
fig <- fig %>% layout(
  polar = list(
    radialaxis = list(
      ticksuffix = "%",
      tickformat = "d", # 控制显示整数,不需要小数可保留该参数
      range = c(0, 5) # 可选,固定径向轴范围
    )
  )
)
fig

需求2:径向轴单位替换为Mio.

先将原始数值除以1e6转换为百万单位,再配置径向轴后缀为Mio.即可覆盖默认的M缩写。
完整示例代码:

# 绘图代码
fig <- plot_ly(
  type = "scatterpolar",
  fill = "toself",
  mode = "lines+markers"
)
for (i in 1:3) {
  d1 <- d %>% filter(Region %in% regions[i])
  fig <- fig %>%
    add_trace(
      r = d1 %>% slice(1:3, 1) %>% pull(Wert) / 1e6, # 转换为百万单位
      theta = d1 %>% slice(1:3, 1) %>% pull(Bezeichnung),
      name = d1 %>% slice(1) %>% pull(Region),
      hovertemplate = paste0(
        "%{fullData.name}<br>",
        "%{theta}<br>",
        "Wert: %{r:.1f} Mio.",
        "<extra></extra>"
      )
    )
}
# 新增径向轴配置
fig <- fig %>% layout(
  polar = list(
    radialaxis = list(
      ticksuffix = "Mio.",
      tickformat = ".1f", # 控制显示1位小数,可按需调整
      range = c(0, 1.5) # 可选,固定径向轴范围
    )
  )
)
fig

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:15:00