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

添加Quarto图标签导致Echarts图表Tooltip格式异常问题

Quarto添加fig标签后Echarts Tooltip对齐错乱的问题解决

问题现象

在Quarto文档中使用echarts4r生成堆叠柱状图时,不给代码块添加fig标签的情况下,Tooltip文本保持正常左对齐;但添加#| label: fig-xxx标签后,Tooltip内的文本出现对齐错乱,标签与数值无法整齐对应。

无fig标签的正常代码示例:

---
title: "test"
date: "`r Sys.Date()`"
---

```{r}
df <- data.frame(
  group = c("Group A", "Group A", "Group B", "Group B", "Group C", "Group C"),
  category = c("really really long catgegory", "medium category", "short", "really really long catgegory", "medium category", "short"),
  value = c(3, 20, 43, 5, 82, 32)
)

df |>
  dplyr::group_by(category) |>
  echarts4r::e_chart(group) |>
  echarts4r::e_bar(value, stack = "stacked") |>
  echarts4r::e_tooltip(trigger = "axis") 

此时Tooltip文本左对齐,各条目排版整齐。

添加fig标签后的异常代码示例:

---
title: "test"
date: "`r Sys.Date()`"
---

```{r}
#| label: fig-1
df <- data.frame(
  group = c("Group A", "Group A", "Group B", "Group B", "Group C", "Group C"),
  category = c("really really long catgegory", "medium category", "short", "really really long catgegory", "medium category", "short"),
  value = c(3, 20, 43, 5, 82, 32)
)

df |>
  dplyr::group_by(category) |>
  echarts4r::e_chart(group) |>
  echarts4r::e_bar(value, stack = "stacked") |>
  echarts4r::e_tooltip(trigger = "axis") 

此时Tooltip内文本对齐错乱,样式不符合预期。

原因

这是由于Quarto在处理带有fig标签的代码块时,会为图表容器注入额外的全局CSS样式,其中的文本对齐规则覆盖了Echarts Tooltip的默认样式,导致排版错乱。

解决方法

方案1:自定义CSS强制恢复左对齐

在文档开头的YAML配置之后,添加自定义CSS代码块,强制设置Tooltip的文本对齐方式:

<style>
.echarts-tooltip,
.echarts-tooltip .echarts-tooltip-item {
  text-align: left !important;
}
</style>

方案2:通过Tooltip格式化函数自定义样式

利用e_tooltip的formatter参数,编写JavaScript函数手动生成Tooltip的HTML内容,确保文本左对齐:

df |>
  dplyr::group_by(category) |>
  echarts4r::e_chart(group) |>
  echarts4r::e_bar(value, stack = "stacked") |>
  echarts4r::e_tooltip(
    trigger = "axis",
    formatter = htmlwidgets::JS("
      function(params) {
        let tooltipContent = `<div>${params[0].axisValue}</div>`;
        params.forEach(item => {
          tooltipContent += `<div>${item.marker} ${item.seriesName}: ${item.value}</div>`;
        });
        return tooltipContent;
      }
    ")
  )

是否为Quarto的Bug?

该问题属于Quarto的CSS样式污染了Echarts内部组件的情况,你可以在Quarto的官方GitHub仓库提交Issue,反馈此问题以确认是否需要官方修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:27:44