如何在本課使用的瀏覽器版 Quarto 模擬器中編輯並渲染(本筆記改寫成在你自己的 .qmd 動手試)
內容筆記
三個組成部分
每個 .qmd 檔都由同樣三種材料構成。下面是一份小而完整的 Quarto 文件,回報一週氣溫的平均:
---
title: "Weekly Temperatures"
format: html
---
## Summary
This week was **warmer** than last week.
```{python}
temps = [18, 21, 24, 19, 23]
sum(temps) / len(temps)
```
一開始符號看起來很多,但拆開來就是三塊,各有職責:
部分
長相
作用
YAML header(YAML 標頭)
檔案最上方兩條 --- 線之間的區塊
設定整份文件的選項,如標題與輸出格式
Markdown text(markdown 文字)
一般文字加上 ##、** 等符號
變成排版後的文字:標題、粗體、清單、連結
Code cells(程式碼格)
以 ```{r} 或 ```{python} 開頭的區塊
渲染時執行,結果顯示在輸出中
Code cells 與 code chunks
用過 R Markdown 的人熟悉的「code chunk(程式碼區塊)」,在 Quarto 叫 code cell,是同一個概念、新名稱。
動手試:第一次渲染
原課程提供瀏覽器內的 Quarto 模擬器(左側編輯器、右側預覽,不用安裝任何東西)。它使用 Quarto 自己的格式化引擎,所以預覽結果與真正的 Quarto 一致;但只能預覽 HTML、也讀不到你電腦裡的檔案。本筆記改成請你在自己的環境操作(第 7 單元會教如何在自己電腦上用 Quarto)。本例用 Python,但這一課不需要你寫任何程式。
---
title: "Markdown Playground"
---
## A heading
Some **bold** text, some *italic* text, and a file name like `report.qmd`.
### A smaller heading
Try making *this sentence* bold instead.
預期結果:## A heading 顯示為較大的章節標題、### A smaller heading 為較小的小節標題;「bold」粗體、「italic」斜體、report.qmd 以程式碼字型顯示。
清單
每行以 - 開頭是項目清單;以「數字加句點」開頭是編號清單:
- Flour
- Milk
- Eggs
1. Mix the batter
2. Heat the pan
3. Cook both sides
Learn more on the [Quarto website](https://quarto.org).
{fig-alt="A line chart of daily high temperatures rising from 15 to 24 degrees over seven days."}
練習:幫食譜加格式
下面這份食譜文字都對、卻完全沒有格式(原課程在模擬器中,按 Render 才更新):
---
title: "Pancakes"
---
Ingredients
1 cup flour
1 cup milk
1 egg
Steps
Whisk everything together.
Cook on a hot pan for 2 minutes per side.
Serve warm.
Do not overmix the batter.
---
title: "Pancakes"
---
## Ingredients
- 1 cup flour
- 1 cup milk
- 1 egg
## Steps
1. Whisk everything together.
2. Cook on a hot pan for 2 minutes per side.
3. Serve warm.
**Do not overmix the batter.**
小測:哪一行才是連結?
要把文字「the docs」連到 https://quarto.org,正確寫法是 the docs。!the docs 是圖片語法;(the docs)[https://quarto.org] 括號顛倒了。
format 選項決定 Quarto 產出哪種檔案,文件其餘內容完全不變。下面是存成 report.qmd 的一份短報告(含標題、清單、表格與一段 Python 畫圖的程式碼格):
---
title: "Quarterly Sales Report"
author: "Ana Lopez"
format: html
---
## Highlights
Sales grew **12%** this quarter, led by the *West* region.
- Two new regions opened
- Returns fell to a record low
- Online orders passed in-store orders
## Sales by Region
| Region | Sales | Change |
|--------|------:|--------|
| North | 120 | Up |
| South | 95 | Down |
| West | 143 | Up |
## Monthly Trend
```{python}
#| echo: false
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 3))
plt.plot(["Jul", "Aug", "Sep"], [102, 115, 128], marker="o")
plt.ylabel("Sales (thousands)")
plt.show()
```
---
title: "Callout Types"
---
::: {.callout-note}
A **note** adds helpful background.
:::
::: {.callout-tip}
## Save time
A **tip** shares a better way to do something. This one has a custom title.
:::
::: {.callout-important}
**Important** information the reader needs.
:::
::: {.callout-warning}
A **warning** about a common mistake.
:::
::: {.callout-caution}
**Caution** before doing something risky.
:::
預期結果:五個不同顏色與圖示的方框;tip 那個顯示自訂標題「Save time」。
Fenced div(圍欄 div)
這個 ::: 語法叫 fenced div。callout 只是其中一種,之後許多 Quarto 功能都用相同的 ::: 樣式。
動手試: 貼入下面文件(原課程此練習場會即時更新),為 East 區新增一列,或把別的欄位改成靠右:
---
title: "Quarterly Sales"
---
@tbl-sales shows sales for each region.
| Region | Sales | Change |
|--------|------:|--------|
| North | 120 | Up |
| South | 95 | Down |
| West | 143 | Up |
: Sales by region {#tbl-sales}
程式碼產生的表格
表格也可以來自程式碼,例如 R 或 Python 的 data frame。給該格 #| label: tbl-... 與 #| tbl-cap: "..." 選項,Quarto 會像 markdown 表格一樣為它編號與加圖說。
邊欄內容(Margin Content)
Quarto 的 HTML 頁面右側有寬闊的邊欄,可放旁註、小圖或某個數字背後的公式。這讓主文維持好讀、細節又近在手邊。把內容包在 ::: {.column-margin} 裡,Quarto 就會把它放在上方那段文字旁邊的邊欄:
The average temperature this week was 22.3 °C, up from
20.1 °C the week before.
::: {.column-margin}
The average of $n$ readings:
$$
\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i
$$
:::
渲染後的頁面如下:主文欄正常顯示兩段關於本週平均氣溫的文字,右側邊欄則是一則灰色小字「The average of n readings:」,下面是平均數公式(x 上有橫線,等於 n 分之一乘以 x_i 從 i=1 到 n 的總和)。
Quarto 網頁:主文欄是兩段關於本週平均氣溫的文字,右側邊欄是灰色小字 The average of n readings 與平均數公式
這裡用到 Quarto 的數學語法:在錢字號之間寫 LaTeX 記號。兩側各一個 $(如 $n$)把數學放在句子內;兩側各兩個 $$(如上面的 $$ 行)讓公式獨立成行。公式不只能放邊欄,在文件任何地方、任何格式都能用。
內建 Quarto,並附 Quarto 擴充功能:Preview 按鈕、語法上色、YAML 選項建議
RStudio
也內建 Quarto,編輯器工具列有 Render 按鈕
其他編輯器
從 quarto.org 下載 Quarto;若編輯器有 Quarto 擴充(如 VS Code)再安裝擴充
本課以 Positron 示範。若要讓 R 或 Python 程式碼格能執行,還需要安裝 R 或 Python,以及 R 的 rmarkdown 套件或 Python 的 jupyter 套件。只有文字與 markdown 的文件則不需要其他東西。
建立並預覽文件
建立文件並預覽只要幾次點擊。原課程是點擊截圖的互動模擬,這裡依序展開四步:
步驟 1:開新檔案。 點 Positron 左上角的 New 按鈕(旁邊是 Open 按鈕;此時 Console 是空的 Python 控制台)。
步驟 2: 打開的 New 選單有 New File、New Folder from Template、New Folder from Git、New Window 等項目,點 New File...。
步驟 3:選檔案類型。 Positron 問你要哪種檔案,清單有 Text File、R File、Python File、Jupyter Notebook、Quarto Document、Quarto Project,選 Quarto Document。
New File 選單:列出 Text File、R File、Python File、Jupyter Notebook、Quarto Document、Quarto Project 六種類型
步驟 4:預覽。 文件在編輯器中開啟後,點編輯器左上方的 Preview。
你的新文件會更空
在 Positron 建立 Quarto 文件時,一開始只有 YAML 標頭:一個 title 與 format: html。原課程模擬中的文件另外加了標題、文字與一個程式碼格,讓預覽有東西可看。
模擬中的文件內容如下(在你自己的 Positron 貼上或自行加入也行):
---
title: "My First Document"
format: html
---
## Hello, Quarto
This document mixes text and code. When you preview it, Quarto
runs the code and shows the result right below it.
```{python}
total = 2 + 3
print(f"The total is {total}")
```
Positron 編輯器中的新 Quarto 文件:YAML 標頭(title: My First Document、format: html)、## Hello, Quarto 標題、一句說明文字、Python 程式碼格 total = 2 + 3,編輯器上方有 Preview 按鈕與 Render on Save 核取方塊
完成後的結果: Positron 渲染文件,並把結果顯示在 Viewer 窗格,緊鄰你的原始檔。程式碼已執行,輸出出現在程式碼下方(內容為「The total is 5」)。你修改原始檔再按 Preview,Viewer 就會更新。
Positron 預覽結果:一側是 first-qmd.qmd 原始碼,另一側的 Viewer 窗格顯示渲染後的標題 My First Document、Hello, Quarto、程式碼與輸出 The total is 5,下方 Terminal 顯示 quarto preview 指令
用鍵盤預覽
在 Positron 按 Ctrl/Cmd + Shift + K 即可預覽,不必動滑鼠。先把文件存成 .qmd,輸出檔才有地方放。
試試更有趣的文件
想預覽更豐富的內容?把下面其中一份複製進新的 Quarto 文件,存成 temps.qmd,按 Preview。它用到 callout、交叉參照與程式碼格畫的圖,都是本課練習過的東西。
R 版(需要 rmarkdown 套件):
---
title: "Weekly Temperatures"
format: html
---
## Summary
The daily highs for the week are in @fig-temps. The warmest reading was **26 °C**.
::: {.callout-note}
Readings from Sunday are estimates.
:::
```{r}
#| label: fig-temps
#| fig-cap: "Daily high temperatures"
#| echo: false
temps <- c(18, 21, 24, 19, 23, 26, 25)
plot(temps, type = "b", xlab = "Day", ylab = "Temperature (°C)")
```
Python 版(需要 jupyter 與 matplotlib 套件):
---
title: "Weekly Temperatures"
format: html
---
## Summary
The daily highs for the week are in @fig-temps. The warmest reading was **26 °C**.
::: {.callout-note}
Readings from Sunday are estimates.
:::
```{python}
#| label: fig-temps
#| fig-cap: "Daily high temperatures"
#| echo: false
import matplotlib.pyplot as plt
temps = [18, 21, 24, 19, 23, 26, 25]
plt.plot(range(1, 8), temps, marker="o")
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.show()
```
--no-watch-inputs:不要每次存檔就重新渲染,Viewer 只在你再按 Preview 時才更新。如果你希望每次存檔都更新,勾選 Preview 旁的 Render on Save。
你也可以在任何終端機自己輸入 Quarto 指令,搭配任何編輯器都能用:
# Render and open a live preview that updates when you save
quarto preview report.qmd
# Render to the format(s) in the YAML header
quarto render report.qmd
# Render to a specific format
quarto render report.qmd --to docx
是 Terminal,不是 Console
Quarto 指令要在 Terminal(終端機)輸入,不是 R 或 Python 的 Console。Console 只懂 R 或 Python 程式碼,在那裡打 quarto render 會報錯。在 Positron,Terminal 是底部面板的一個分頁,就在 Console 旁邊。
preview 與 render 的分工
quarto preview 用於寫作:它持續執行,你自己在終端機輸入時,每次存檔都會刷新輸出。quarto render 用於完稿:產出最終檔案後就結束。
Run Cell 與 Preview 的差別
在 Positron,每個程式碼格上方都有 Run Cell 連結,寫作時很方便:不必等整份文件,可以一次試一個格子。但 Run Cell 與 Preview 在不同的地方執行你的程式碼,彼此不共用結果。Run Cell 把程式碼送到 Console;Preview 則在 Terminal 執行 quarto preview,那是另一個獨立程式、會開啟自己的 session。
Run Cell
Preview
程式碼在哪裡執行
Console,也就是你的互動式 session
全新的 session,與 Console 分開
執行什麼
只有那個格子
每個格子,由上到下依序
能用到什麼
你到目前為止在 Console 建立的任何東西
只有文件本身建立的東西
這造成一個經典的意外。假設你在 Console 探索,並在那裡載入資料:
import pandas as pd
sales = pd.read_csv("sales.csv")
文件中有一個格子是 sales.head()。你按 Run Cell 成功了,因為 sales 存在於 Console。然後你按 Preview,卻失敗並出現 NameError: name 'sales' is not defined。因為 Preview 的全新 session 從沒看過你的 Console,所以那裡沒有 sales。R 也一樣,錯誤訊息類似 object 'sales' not found。
::: {.callout-tip}
A callout: note, tip, important, warning, or caution.
:::
@fig-sales shows the trend.
| Region | Sales |
|--------|------:|
| North | 120 |
: Sales by region {#tbl-sales}
渲染方式(單元 7)
在哪裡
怎麼做
Positron
Preview 按鈕,或 Ctrl/Cmd + Shift + K
Positron,所有格式
Command Palette 的 Quarto: Render Document
Terminal
quarto preview file.qmd 或 quarto render file.qmd --to docx
Extensions 檢視:頂端是「Search Extensions in Marketplace」搜尋框,下方 INSTALLED 清單(17 個)列出 Air - R Language Support(R 格式化與 language server,Posit Software, PBC 發行)、Black Formatter、GitHub Pull Requests、Jupyter 等,每項右側有齒輪圖示
預設來源:P3M
Positron 預設從 Posit Public Package Manager(P3M) 安裝 extensions,由 Posit 自己的基礎設施提供,確保穩定散布。其目錄與 Open VSX(Visual Studio Marketplace 的開源、中立替代品)相同。若想直接用 Open VSX,切換 positron.extensions.gallerySource 設定即可。
Activity bar 切換 side bar 的檢視:Explorer、Search、Source Control、Run and Debug、Extensions、Packages、Posit Assistant、Data Connections(預覽功能,需啟用 dataConnections.enabled)。
資料不只存在檔案,很多在資料庫與資料倉儲。Data Connections 是 Positron 主側邊欄的一個檢視,可:儲存資料庫/資料倉儲連線、瀏覽內容(catalog、schema、table、view、column)、在 Data Explorer 預覽表格、產生 Python/R 連線程式碼。
Positron 能替你建好結構良好的專案資料夾。開啟左上角 New 下拉選單(或右上角 Folder Selector),選 New Folder from Template。New 選單內容依序為:New File、New Folder from Template、New Folder from Git、New Window。
New 下拉選單展開:New File、New Folder from Template(被選中)、New Folder from Git、New Window