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

Quarto文档中ggplot2离散变量多图主题颜色一致性问题

问题

在Quarto HTML文档中配置主题时,先在YAML里设置了darkly主题,再运行thematic::thematic_rmd()配置thematic,但遇到两个问题:

  1. 过滤掉因子某一水平后,用scale_color_discrete(limits=levels(mtcars$cyl))试图保持颜色一致,结果主题颜色被破坏。
  2. 绘图没有遵循YAML中设置的主题。

示例Quarto文档代码如下:

---
title: "Consistent colours"
format:
  html:
    theme: darkly
---

## Example

```{r}
#| label: setup

library(ggplot2)
library(dplyr)

thematic::thematic_rmd()

data(mtcars, package="datasets")
mtcars$cyl = as.factor(mtcars$cyl)

Plot with all the factor levels:

ggplot(mtcars, aes(x=hp, y=mpg, color=cyl)) + geom_point(size=5)

Plot with one less factor level:

ggplot(filter(mtcars, cyl != "6"), aes(x=hp, y=mpg, color=cyl)) + geom_point(size=5) + scale_color_discrete(limits=levels(mtcars$cyl), drop=TRUE)
## 解决方案
### 问题根源
- `thematic_rmd()`会接管ggplot的颜色标度,直接调用`scale_color_discrete()`会覆盖thematic的主题颜色映射,导致主题失效。
- thematic需要明确配置主题继承,才能和Quarto的YAML主题同步。

### 修复步骤
1. 不要手动调用`scale_color_discrete()`,改用thematic提供的方式维护颜色一致性。
2. 在`thematic_rmd()`中添加`inherit = TRUE`参数,确保完全继承Quarto的HTML主题样式。
3. 提前获取thematic的离散颜色映射,绑定到因子所有水平,过滤后仍能保持颜色一致。

### 修改后的代码示例
```yaml
---
title: "Consistent colours"
format:
  html:
    theme: darkly
---

## Example

```{r}
#| label: setup
#| include: false

library(ggplot2)
library(dplyr)
library(thematic)

# 开启thematic并继承Quarto主题
thematic_rmd(inherit = TRUE)

data(mtcars, package="datasets")
mtcars$cyl = as.factor(mtcars$cyl)
# 获取thematic主题对应的离散颜色,绑定到cyl的所有水平
cyl_colors = thematic_get()$discrete_colors(3)
names(cyl_colors) = levels(mtcars$cyl)

Plot with all the factor levels:

ggplot(mtcars, aes(x=hp, y=mpg, color=cyl)) + geom_point(size=5)

Plot with one less factor level:

ggplot(filter(mtcars, cyl != "6"), aes(x=hp, y=mpg, color=cyl)) + 
  geom_point(size=5) +
  # 使用主题颜色保持一致性
  scale_color_manual(values = cyl_colors)
### 说明
- `thematic_rmd(inherit = TRUE)`确保绘图完全同步Quarto的主题样式,包括颜色、字体、背景色等。
- 提前获取主题离散颜色并绑定到因子水平,既保证过滤后的绘图颜色和完整数据一致,又不会破坏thematic的主题控制。

内容的提问来源于stack exchange,提问作者Jan Tabacek
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:57:22