```{r}
#| message: false
#| output: false
library(palmerpenguins)
library(here)
root_dir <- "/Users/jihong/Documents/Projects/website-jihong"
data(penguins)
write.csv(penguins, file = here(root_dir, "notes", '2024-03-10-Quarto-Observable-JS', 'palmer-penguins.csv'))
```
Observable JS in Quarto document
OJS
Quarto
The documents regarding how to use Observable Javascript in Quarto is extremely lacking. Two main sources for this topic are quarto.org and quarto dashboard.
The note reproduces the example shown in quarto.org and displays some issues and their solutions I encountered.
Example
Currently, OJS doesn’t work interactively with RStudio (see the github discussion). As the document shows, the example based on Allison Horst’s Palmer Penguins.
{ojs}
```= FileAttachment('palmer-penguins.csv').csv({ typed: true})
data ```
{ojs}
```= Inputs.range(
viewof bill_length_min [32, 50],
{value: 35, step: 1, label: "Bill length (min):"}
)
= Inputs.checkbox(
viewof islands ["Torgersen", "Biscoe", "Dream"],
{ value: ["Torgersen", "Biscoe"],
: "Islands:"
label}
)
```
{ojs}
```= data.filter(function(penguin) {
filtered return bill_length_min < penguin.bill_length_mm &&
.includes(penguin.island);
islands})
```
{ojs}
```.rectY(filtered,
Plot.binX(
Plot{y: "count"},
{x: "body_mass_g", fill: "species", thresholds: 20}
))
.plot({
: {
facet: filtered,
data: "sex",
x: "species",
y: 80
marginRight},
: [
marks.frame(),
Plot]
}
)
```
Transfer from R to OJS
There’s a nice post from Duke library, introducing a nicer way of embedding R and OJS. The getting-started page of OJS official website has many examples of different types of plots.
```{r}
#| output: false
ojs_define(penguins = penguins)
```
Dot (scatter) plot
{ojs}
```.plot({
Plot: true,
grid: 10,
inset: [
marks.dot(transpose(penguins), {
Plot: "bill_length_mm",
x: "bill_depth_mm",
y: "species"
stroke}),
]
})
```
Histgram
```{r}
#| output: false
library(tidyverse)
penguins_summarized <- penguins |>
mutate(body_mass_group = cut(body_mass_g / 1000, 10)) |>
group_by(body_mass_group) |>
summarise(frequency = n())
ojs_define(penguins_summarized = penguins_summarized)
```
{ojs}
```.plot({
Plot: {padding: 0.1},
x: 50,
marginTop: 0,
marginRight: 50,
marginBottom: [
marks.barY(transpose(penguins_summarized), {x: "body_mass_group", y: "frequency", dx: 2, dy: 2}),
Plot.barY(transpose(penguins_summarized), {x: "body_mass_group", y: "frequency", fill: "green", dx: -2, dy: -2})
Plot]
})
```