2022/9/19

VEGA-lite

vega 是一種描述圖表的語法,符合 JSON spec。d3.js 是比較低階的語法,需要用 javascript 處理。vega 只需要 JSON 文件,就撰寫出各式圖表。如果只需要一些常用的圖表,還可以使用 vega-lite,會比 vega 更簡捷。

vega 跟 d3.js 一樣,也是 Washington Interactive Data Lab 開發的,所以 vega 的底層是 d3.js。vega 並不是要取代 d3.js,而是在 d3.js 的基礎上,提供更高階的圖表語言。而且 JSON 更容易用程式碼產生出來。

可以直接從 Example Gallery | Vega-Lite 查看支援的圖表,然後根據自己想要使用的圖表,看範例去修改。

BarChart

Simple bar chart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
      {"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
      {"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"}
  }
}

render

Arrgegate Bar Chart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A bar chart showing the US population distribution of age groups in 2000.",
  "height": {"step": 17},
  "data": { "url": "https://vega.github.io/vega-lite/examples/data/population.json"},
  "transform": [{"filter": "datum.year == 2000"}],
  "mark": "bar",
  "encoding": {
    "y": {"field": "age"},
    "x": {
      "aggregate": "sum", "field": "people",
      "title": "population"
    }
  }
}

render

Group Bar Chart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"category":"A", "group": "x", "value":0.1},
      {"category":"A", "group": "y", "value":0.6},
      {"category":"A", "group": "z", "value":0.9},
      {"category":"B", "group": "x", "value":0.7},
      {"category":"B", "group": "y", "value":0.2},
      {"category":"B", "group": "z", "value":1.1},
      {"category":"C", "group": "x", "value":0.6},
      {"category":"C", "group": "y", "value":0.1},
      {"category":"C", "group": "z", "value":0.2}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "category"},
    "y": {"field": "value", "type": "quantitative"},
    "xOffset": {"field": "group"},
    "color": {"field": "group"}
  }
}

render

Stacked Bar Chart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "https://vega.github.io/vega-lite/examples/data/seattle-weather.csv"},
  "mark": "bar",
  "encoding": {
    "x": {
      "timeUnit": "month",
      "field": "date",
      "type": "ordinal",
      "title": "Month of the year"
    },
    "y": {
      "aggregate": "count",
      "type": "quantitative"
    },
    "color": {
      "field": "weather",
      "type": "nominal",
      "scale": {
        "domain": ["sun", "fog", "drizzle", "rain", "snow"],
        "range": ["#e7ba52", "#c7c7c7", "#aec7e8", "#1f77b4", "#9467bd"]
      },
      "title": "Weather type"
    }
  }
}

render

Histrogram

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "https://vega.github.io/vega-lite/examples/data/movies.json"},
  "mark": "bar",
  "encoding": {
    "x": {
      "bin": true,
      "field": "IMDB Rating"
    },
    "y": {"aggregate": "count"}
  }
}

render

ScatterPlot

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A scatterplot showing horsepower and miles per gallons for various cars.",
  "data": {"url": "https://vega.github.io/vega-lite/examples/data/cars.json"},
  "mark": "point",
  "encoding": {
    "x": {"field": "Horsepower", "type": "quantitative"},
    "y": {"field": "Miles_per_Gallon", "type": "quantitative"}
  }
}

render

LineChart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Stock prices of 5 Tech Companies over Time.",
  "data": {"url": "https://vega.github.io/vega-lite/examples/data/stocks.csv"},
  "mark": {
    "type": "line",
    "point": true
  },
  "encoding": {
    "x": {"timeUnit": "year", "field": "date"},
    "y": {"aggregate":"mean", "field": "price", "type": "quantitative"},
    "color": {"field": "symbol", "type": "nominal"}
  }
}

render

AreaChart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 300,
  "height": 200,
  "data": {"url": "https://vega.github.io/vega-lite/examples/data/unemployment-across-industries.json"},
  "mark": "area",
  "encoding": {
    "x": {
      "timeUnit": "yearmonth", "field": "date",
      "axis": {"format": "%Y"}
    },
    "y": {
      "aggregate": "sum", "field": "count",
      "title": "count"
    }
  }
}

render

Table-based Plots

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "https://vega.github.io/vega-lite/examples/data/cars.json"},
  "mark": "rect",
  "encoding": {
    "y": {"field": "Origin", "type": "nominal"},
    "x": {"field": "Cylinders", "type": "ordinal"},
    "color": {"aggregate": "mean", "field": "Horsepower"}
  },
  "config": {
    "axis": {"grid": true, "tickBand": "extent"}
  }
}

render

Circulat Plots

PieChart

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple pie chart with labels.",
  "data": {
    "values": [
      {"category": "a", "value": 4},
      {"category": "b", "value": 6},
      {"category": "c", "value": 10},
      {"category": "d", "value": 3},
      {"category": "e", "value": 7},
      {"category": "f", "value": 8}
    ]
  },
  "encoding": {
    "theta": {"field": "value", "type": "quantitative", "stack": true},
    "color": {"field": "category", "type": "nominal", "legend": null}
  },
  "layer": [{
    "mark": {"type": "arc", "outerRadius": 80}
  }, {
    "mark": {"type": "text", "radius": 90},
    "encoding": {
      "text": {"field": "category", "type": "nominal"}
    }
  }]
}

render

References

用 VEGA 資料視覺化

A High-Level Grammar of Interactive Graphics | Vega-LiteA High-Level Grammar of Interactive Graphics | Vega-Lite

用 Reveal.js 製作 Slide

通常使用 reveal.js 會需要用 web server 將 js, css, html 放在上面,以便遠端存取這些資源,或是搭配 nodejs 使用。不過也可以將 GitHub - hakimel/reveal.js: The HTML Presentation Framework clone 下來,然後複製 dist 與 plugin 目錄的資料,就可以直接使用。

用 JS 製作 slide,有一些優點是 PowerPoint 沒有的,因為是 JS,所以可以做 code highlight,還有更彈性的動畫功能,可更正確地以 MathJS 顯示數學方程式,簡報也因為 script 化,size 會縮小很多,啟動也比較快。Reveal.js 以 plugin 的方式,提供外掛的功能。

內建有這些 plugin

Name Description
RevealHighlight Syntax highlighted code.
plugin/highlight/highlight.js
RevealMarkdown Write content using Markdown.
plugin/markdown/markdown.js
RevealSearch Press CTRL+Shift+F to search slide content.
plugin/search/search.js
RevealNotes Show a speaker view in a separate window.
plugin/notes/notes.js
RevealMath Render math equations.
plugin/math/math.js
RevealZoom Alt+click to zoom in on elements (CTRL+click in Linux).
plugin/zoom/zoom.js

簡報的 theme 有: Black (default)WhiteLeagueSkyBeigeSimple SerifBloodNightMoonSolarized

這是兩頁簡單的投影片

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

        <title>slide</title>

        <link rel="stylesheet" href="dist/reset.css">
        <link rel="stylesheet" href="dist/reveal.css">
        <link rel="stylesheet" href="dist/theme/black.css">

        <!-- Theme used for syntax highlighted code -->
        <link rel="stylesheet" href="plugin/highlight/monokai.css">
    </head>
    <body>
        <div class="reveal">
            <div class="slides">
                <section>Slide 1</section>
                <section>Slide 2</section>
            </div>
        </div>

        <script src="dist/reveal.js"></script>
        <script src="plugin/notes/notes.js"></script>
        <script src="plugin/markdown/markdown.js"></script>
        <script src="plugin/highlight/highlight.js"></script>
        <script>
            // More info about initialization & config:
            // - https://revealjs.com/initialization/
            // - https://revealjs.com/config/
            Reveal.initialize({
                hash: true,

                // Learn about plugins: https://revealjs.com/plugins/
                plugins: [ RevealMarkdown, RevealHighlight, RevealNotes ]
            });
        </script>
    </body>
</html>

如果不下載 reveal.js 的 repository,也可以使用 reveal.js - Libraries - cdnjs

去掉 library 及 css,投影片的部分為

        <div class="reveal">
            <div class="slides">
                <section>Slide 1</section>
                <section>Slide 2</section>
            </div>
        </div>

initialization

library 初始化有以下這些設定值

<script>
      Reveal.initialize({
          // 參數設定[註1]
          controls: true, // 控制按鈕
          controlsTutorial: true, // 引導初學者功能
          controlsLayout: 'bottom-right', // 控制按鈕位置
          controlsBackArrows: 'faded', // 返回按鈕顯示方式
          progress: true, // 簡報進度條
          slideNumber: true, // 簡報當前頁碼
          history: false, // 所有動作儲存在歷史紀錄
          keyboard: true, // 鍵盤快捷鍵
          overview: true, // 簡報導覽模式
          center: true, // 簡報垂直置中
          touch: true, // 觸碰模式
          loop: false, // 循環模式
          rtl: false, // 簡報方向為RTL模式
          shuffle: false, // 簡報顯示順序為隨機模式
          autoPlayMedia: null, // 簡報內影音媒體為自動播放
          autoSlide: 0, // 自動切換的秒數,0秒代表不自動
          autoSlideStoppable: true, // 使用者在操作時停止自動切換
          autoSlideMethod: Reveal.navigateNext, // 自動切換觸發的函式
          mouseWheel: false, // 滑鼠滾輪可以切換簡報
          transition: 'slide', // 轉場動畫
          transitionSpeed: 'default', // 轉場速度
          backgroundTransition: 'fade', // 簡報背景的轉場動畫
          parallaxBackgroundImage: '', // 背景視差圖片
          parallaxBackgroundSize: '', // 背景視差圖片尺寸(單位: 像素)
          parallaxBackgroundHorizontal: null, // 水平背景視差,0為停止視差,null為自動計算(單位: 像素)
          parallaxBackgroundVertical: null // 垂直背景視差,0為停止視差,null為自動計算(單位: 像素)
      });
  </script>

Vertical Slide

<section>Horizontal Slide</section>
<section>
  <section>Vertical Slide 1</section>
  <section>Vertical Slide 2</section>
</section>

Auto-Animate

切換頁面後,以動畫方式顯示投影片

<section data-auto-animate>
  <h1>Auto-Animate</h1>
</section>
<section data-auto-animate>
  <h1 style="margin-top: 100px; color: red;">Auto-Animate</h1>
</section>

Auto-Slide

自動播放投影片

// Slide every five seconds
Reveal.initialize({
  autoSlide: 5000,
  loop: true
});

Speaker View

showNotes 要設定為 true

<section>
  <h2>Some Slide</h2>

  <aside class="notes">
    Shhh, these are your private notes 📝
  </aside>
</section>

Slide Number

顯示簡報頁碼

Reveal.initialize({ slideNumber: true });

Touch Navigation

在 touch screen 是否能用滑動方式切換投影片

Reveal.initialize({
  touch: false
})

PDF Export

在簡報網址後面加上 ?print-pdf,可將簡報顯示為列印模式,然後就可以用 chrome 列印為 PDF

http://localhost:8000/?print-pdf

Overview Mode

在簡報中用 »ESC« or »O« 按鍵,可切換 Overview mode

Fullscreen Mode

在簡報中用 »F« 按鍵,可切換 Fullscreen

Example

一些簡報的範例

<div class="reveal">
<div class="slides">
    <section>
        <h1>Reveal.js Slide</h1>
        <p>簡報 demo</p>
    </section>
    <section>
        <h2>link</h2>
        <p>這是<a href="https://www.google.com/" target="_blank">測試連結</a></p>
    </section>
    <section>
        <h2>code highlight</h2>
        <pre><code class="hljs java" data-trim contenteditable data-line-numbers>
public class HelloWorld
{
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
        </code></pre>
    </section>

    <section data-markdown>
        <h2>markdown 的 math 聯立方程式</h2>
`$$ \begin{cases}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{cases} $$`
    </section>

    <section>
        <h2>The Lorenz Equations</h2>
\[\begin{aligned}
  \dot{x} & = \sigma(y-x) \\
  \dot{y} & = \rho x - y - xz \\
  \dot{z} & = -\beta z + xy
  \end{aligned} \]
    </section>

    <section data-markdown>
        <textarea data-template>
        ## Slide 1
        A paragraph with some text and a [link](https://www.google.com).
        ---
        ## Slide 2
        ---
        ## Slide 3
        </textarea>
    </section>
</div>
</div>

References

使用reveal.js製作精美的網頁版PPT | 程式前沿

使用 reveal.js 建立投影片

用 Markdown 與 Reveal.js 來製作簡報 - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天

reveal.js:用網頁製作簡報的 HTML5 架構 - G. T. Wang

2022/9/8

flowchat.js

MarkText 除了能用 mermaid 的 flowchart 以外,還支援 flowchart.js

語法

[] 裡面的 item 是 optional

nodeName=>nodeType: nodeText[|flowstate][:>urlLink]

nodeName 是 node variable

nodeType 定義該 node 的類型

nodeText 是 node 裡面的文字

flowstate 為 optional,用 |指定多個 style

urlLink 為 optional,用 :> 指定 link,在 MarkText 裡面,link 沒有作用。但輸出為 pdf 後,可在pdf 裡面的圖表上使用 link,連接到該網頁。

Node Types

start 為 first node

end 為 last node

operatoin 是方塊文字,代表一個動作

inputoutput 是 IO

subroutine 是另一個 flowchart

condition 為 logical condition

parallel 是同時發生的兩個 flow

Connections

<node variable name>[(<specification1>[, <specification2])]-><node variable name>[[(<specification1>[, <specification2])]-><node variable name>]

[] 裡面的 item 是 optional

用 -> 連接 nodes

ex:

nodeVar1->nodeVar2
nodeVar2->nodeVar3

或
nodeVar1->nodeVar2->nodeVar3

Directions

離開 node 的 connection 的方向

  • left

  • right

  • top

  • down

ex:

startVar(<direction>)->nextNode
operationVar(<direction>)->nextNode

conditionalVar(yes, <direction>)->nextNode1
conditionalVar(no,  <direction>)->nextNode2

parallelVar(path1, <direction>)->nextNode1
parallelVar(path2, <direction>)->nextNode2
parallelVar(path3, <direction>)->nextNode3

Example

st=>start: Start:>http://www.google.com[blank]
e=>end:>http://www.google.com
op1=>operation: My Operation
sub1=>subroutine: My Subroutine
cond=>condition: Yes or No?:>http://www.google.com
io=>inputoutput: catch something...
para=>parallel: parallel tasks

st->op1->cond
cond(yes)->io->e
cond(no)->para
para(path1, bottom)->sub1(right)->op1
para(path2, top)->op1

render

References

flowchart.js

GitHub - adrai/flowchart.js: Draws simple SVG flow chart diagrams from textual representation of the diagram

2022/9/5

Mermaid - Class Diagram

classDiagram
      Animal <|-- Duck
      Animal <|-- Fish
      Animal <|-- Zebra
      Animal : +int age
      Animal : +String gender
      Animal: +isMammal()
      Animal: +mate()
      class Duck{
          +String beakColor
          +swim()
          +quack()
      }
      class Fish{
          -int sizeInFeet
          -canEat()
      }
      class Zebra{
          +bool is_wild
          +run()
      }

render

語法

class 包含三個部分

  • 最上面是 class name,第一個字母是大寫

  • 中間是 attributes,第一個字母小寫,可加上類別

  • 最下面是 operations,第一個字母小寫

classDiagram
    class BankAccount
    BankAccount : +String owner
    BankAccount : +Bigdecimal balance
    BankAccount : +deposit(amount)
    BankAccount : +withdrawl(amount)

render

定義 class

  • 關鍵字為 class ex: class Animal

  • 兩個 class 之間有繼承關係 ex: Animal <|-- Dog

classDiagram
    class Animal
    Animal <|-- Dog

render

定義 members

有兩種寫法

classDiagram
 class BankAccount
 BankAccount : +String owner
 BankAccount : +BigDecimal balance
 BankAccount : +deposit(amount)
 BankAccount : +withdrawal(amount)

class BankAccount2{
    +String owner
    +BigDecimal balance
    +deposit(amount)
    +withdrawl(amount)
}

render

method 後面可加上 return type

classDiagram
class BankAccount{
    +String owner
    +BigDecimal balance
    +deposit(amount) bool
    +withdrawl(amount) int
}

GenericType: 在 Java 有時會用到 List<String> 這樣的資料結構,這邊用這樣的語法表示 List~string~

classDiagram
class Square~Shape~{
    int id
    List~Int~ position
    setPoints(List~Int~ points)
    getPoints() List~Int~
}

Square : -List~String~ messages
Square : +setMessages(List~String~ messages)
Square : +getMessages() List~String~

render

Visibility 有四種

  • + Public
  • - Private
  • # Protected
  • ~ Package/Internal

另外可在 method 與 field 後面加上 classifiers

  • * Abstract method e.g.: someAbstractMethod()*
  • $ Static method e.g.: someStaticMethod()$
  • $ Static field e.g.: String someField$

## 定義關係

[classA][Arrow][ClassB]
[classA][Arrow][ClassB]:LabelText
Type Description
<\ --
*-- Composition
o-- Aggregation
--> Association
-- Link (Solid)
..> Dependency
..\ >
.. Link (Dashed)

example : 後面是 label,可不填寫

classDiagram
classA --|> classB : Inheritance
classC --* classD : Composition
classE --o classF : Aggregation
classG --> classH : Association
classI -- classJ : Link(Solid)
classK ..> classL : Dependency
classM ..|> classN : Realization
classO .. classP : Link(Dashed)

render

classDiagram
classA <|-- classB : implements
classC *-- classD : composition
classE o-- classF : association

render

雙向關係

[Relation Type][Link][Relation Type]

Relation Type:

Type Description
<\
* Composition
o Aggregation
> Association
< Association
\ >

Link

Type Description
-- Solid
.. Dashed

cardinality/multiplicity on relations

  • 1 Only 1
  • 0..1 Zero or One
  • 1..* One or more
  • * Many
  • n n {where n>1}
  • 0..n zero to n {where n>1}
  • 1..n one to n {where n>1}

語法

[classA] "cardinality1" [Arrow] "cardinality2" [ClassB]:LabelText

ex:

classDiagram
    Customer "1" --> "*" Ticket
    Student "1" --> "1..*" Course
    Galaxy --> "many" Star : Contains

render

Annotations on classes

用在 interface 或 abstract class

  • <<Interface>> To represent an Interface class
  • <<abstract>> To represent an abstract class
  • <<Service>> To represent a service class
  • <<enumeration>> To represent an enum

ex

classDiagram

class Shape
<<interface>> Shape
Shape : noOfVertices
Shape : draw()

class Color
<<enumeration>> Color
Color: RED
Color: BLUE
Color: GREEN
Color: WHITE
Color: BLACK

render