Replies: 4 comments 2 replies
-
In which context? HTML? |
Beta Was this translation helpful? Give feedback.
-
It'd be nice to be able to follow this approach* (from Plot's online documentation) https://twitter.com/mbostock/status/1653069773645938689
*(I mean, beyond Observable cells) |
Beta Was this translation helpful? Give feedback.
-
For R code chunks, this trick might be useful to generate both light and dark figures at once:
I have not yet found the right CSS/js trick to switch between the two files when dark/light mode is enabled by the quarto toggle (as opposed to the browser mode); quarto doesn't seem to rely on |
Beta Was this translation helpful? Give feedback.
-
From @baptiste code, here is a complete working solution using JavaScript1 also using the recommended YAML syntax for options. JavaScript code// Author: Mickaël Canouil
// Version: <1.0.0>
// Description: Change image src depending on body class (quarto-light or quarto-dark)
// License: MIT
function updateImageSrc() {
var bodyClass = window.document.body.classList;
var images = window.document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
var src = image.src;
var newSrc = src;
if (bodyClass.contains('quarto-light') && src.includes('-dark')) {
newSrc = src.replace('-dark', '-light');
} else if (bodyClass.contains('quarto-dark') && src.includes('-light')) {
newSrc = src.replace('-light', '-dark');
}
if (newSrc !== src) {
image.src = newSrc;
}
}
}
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
updateImageSrc();
}
});
});
observer.observe(window.document.body, {
attributes: true
});
updateImageSrc(); Quarto document---
title: "Untitled"
theme:
light: flatly
dark: darkly
knitr:
opts_chunk:
dev: [svg, darksvg]
fig.ext: [.-light.svg, .-dark.svg]
include-after-body:
text: |
<script type="application/javascript" src="image-dark-light.js"></script>
---
```{r}
#| echo: false
library(ggplot2)
library(ggdark)
darksvg <- function(file, width, height) {
on.exit(ggplot2::reset_theme_settings())
theme_set(dark_mode(theme_get()))
ggsave(filename = file, width = width, height = height, dev = "svg", bg = "transparent")
}
```
```{r}
library(palmerpenguins)
ggplot(data = penguins) +
aes(x = flipper_length_mm, y = body_mass_g) +
geom_point(
mapping = aes(
colour = species,
shape = species
),
alpha = 0.8
) +
scale_colour_manual(values = c("darkorange", "purple", "cyan4")) +
labs(
x = "Flipper length (mm)",
y = "Body mass (g)",
color = "Penguin species",
shape = "Penguin species"
)
``` dark-light.mov@baptiste About Footnotes
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible to have different figures for light and dark themes, something like #gh-dark-mode-only?
Beta Was this translation helpful? Give feedback.
All reactions