Kotlin Notebookでサポートされている出力形式
Kotlin Notebookは、テキスト、HTML、画像など、さまざまな出力タイプをサポートしています。外部ライブラリの助けを借りて、出力オプションを拡張し、チャート、スプレッドシートなどを用いてデータを可視化することができます。
各出力は、Jupiter MIMEタイプを何らかのデータにマッピングするJSONオブジェクトです。このマップから、Kotlin NotebookはサポートされているMIMEタイプの中から最も優先度の高いものを選択し、次のようにレンダリングします。
- テキストは
text/plainMIMEタイプを使用します。 - BufferedImageクラスは、Base64文字列にマッピングされた
image/pngMIMEタイプを使用します。 - ImageクラスとLaTeX形式は、内部に
imgタグを持つtext/htmlMIMEタイプを使用します。 - Kotlin DataFrameテーブルとKandyプロットは、静的HTMLまたは画像によって支えられている独自の内部MIMEタイプを使用します。これにより、GitHub上でそれらを表示することができます。
マッピングを手動で設定することができます。例えば、Markdownをセル出力として使用する場合などです。
MimeTypedResult(
mapOf(
"text/plain" to "123",
"text/markdown" to "# HEADER",
//other mime:value pairs
)
)あらゆる種類の出力を表示するには、DISPLAY()関数を使用します。これにより、複数の出力を組み合わせることも可能になります。
DISPLAY(HTML("<h2>Gaussian distribution</h2>"))
DISPLAY(LATEX("f(x) = \\frac{1}{\\sigma \\sqrt{2\\pi}} \\cdot e^{-\\frac{(x - \\mu)^2}{2\\sigma^2}}"))
val experimentX = experimentData.map { it.key }
val experimentY = experimentData.map { it.value }
DISPLAY(plot {
bars {
x(experimentX)
y(experimentY)
}
})
テキスト
プレーンテキスト
最もシンプルな出力タイプはプレーンテキストです。これは、プリント文、変数、またはコードからのテキストベースの出力に使用されます。
val a1: Int = 1
val a2: Int = 2
var a3: Int? = a1 + a2
"My answer is $a3"
- セルの結果がレンダリングされ、いずれかの出力タイプとして表示できない場合、
toString()関数を使用してプレーンテキストとして出力されます。 - コードにエラーが含まれている場合、Kotlin Notebookはエラーメッセージとトレースバックを表示し、デバッグのための洞察を提供します。
リッチテキスト
リッチテキストを使用するには、Markdownタイプのセルを選択します。これにより、リスト、テーブル、フォントスタイル、コードブロックなどを利用して、MarkdownとHTMLマークアップでコンテンツをフォーマットできます。HTMLにはCSSスタイルやJavaScriptを含めることができます。
## Line magics
| Spell | Description | Example |
|------------------------------------|------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| <code>%use</code> | Injects code for supported libraries: artifact resolution, default imports, initialization code, type renderers. | <code>%use klaxon(5.5), lets-plot</code> |
| <code>%trackClasspath</code> | Logs any changes of current classpath. Useful for debugging artifact resolution failures. | <code>%trackClasspath [on |off]</code> |
| <code>%trackExecution</code> | Logs pieces of code that are going to be executed. Useful for debugging of libraries support. | <code>%trackExecution [all|generated|off]</code> |
| <code>%useLatestDescriptors</code> | Use latest versions of library descriptors available. By default, bundled descriptors are used. | <code>%useLatestDescriptors [on|off]</code> |
| <code>%output</code> | Output capturing settings. | <code>%output --max-cell-size=1000 --no-stdout --max-time=100 --max-buffer=400</code> |
| <code>%logLevel</code> | Set logging level. | <code>%logLevel [off|error|warn|info|debug]</code> |
<ul><li><a href="https://github.com/Kotlin/kotlin-jupyter/blob/master/docs/magics.md">Learn more detailes about line magics</a>.</li>
<li><a href="https://github.com/Kotlin/kotlin-jupyter/blob/master/docs/magics.md">See the full list of supported libraries</a>.</li></ul>
HTML
Kotlin NotebookはHTMLを直接レンダリングし、スクリプトを実行したり、ウェブサイトを埋め込んだりすることもできます。
HTML("""
<p>Counter: <span id="ctr">0</span> <button onclick="inc()">Increment</button></p>
<script>
function inc() {
let counter = document.getElementById("ctr")
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
</script>
""")
スクリプトを実行できるようにするには、ファイルの先頭でノートブックを信頼済みとしてマークしてください。
画像
Kotlin Notebookを使用すると、ファイルからの画像、生成されたグラフ、またはその他の視覚メディアを表示できます。静止画像は、.png、jpeg、.svgなどの形式で表示できます。
Buffered images
デフォルトでは、BufferedImageクラスを使用して画像を表示できます。
import java.awt.Color
import java.awt.image.BufferedImage
val width = 300
val height = width
val image = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
val graphics = image.createGraphics()
graphics.background = Color.BLACK
graphics.clearRect(0, 0, width, height)
graphics.setRenderingHint(
java.awt.RenderingHints.KEY_ANTIALIASING,
java.awt.RenderingHints.VALUE_ANTIALIAS_ON
)
graphics.color = Color.WHITE
graphics.fillRect(width / 10, height * 8 / 10, width * 10 / 20, height / 10)
graphics.dispose()
ロードされた画像
lib-extライブラリの助けを借りて、標準のJupyter機能を拡張し、ネットワークからロードされた画像を表示できます。
%use lib-ext(0.11.0-398)Image("https://kotlinlang.org/docs/images/kotlin-logo.png", embed = false).withWidth(300)
埋め込み画像
ネットワークからロードされた画像の欠点は、リンクが切れたり、ネットワーク接続が失われたりすると、画像が表示されなくなることです。この問題を回避するには、埋め込み画像を使用します。例:
val kotlinMascot = Image("https://blog.jetbrains.com/wp-content/uploads/2023/04/DSGN-16174-Blog-post-banner-and-promo-materials-for-post-about-Kotlin-mascot_3.png", embed = true).withWidth(400)
kotlinMascot
数式と方程式
LaTeX形式(学術分野で広く使用されている組版システム)を使用して数式や方程式をレンダリングできます。
Jupyterカーネルの機能を拡張する
lib-extライブラリをノートブックに追加します。none%use lib-ext(0.11.0-398)新しいセルで、数式を実行します。
noneLATEX("c^2 = a^2 + b^2 - 2 a b \\cos\\alpha")
データフレーム
Kotlin Notebookを使用すると、データフレームで構造化されたデータを可視化できます。
ノートブックにKotlin DataFrameライブラリを追加します。
none%use dataframeデータフレームを作成し、新しいセルで実行します。
kotlinval months = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) // Sales data for different products and months: val salesLaptop = listOf(120, 130, 150, 180, 200, 220, 240, 230, 210, 190, 160, 140) val salesSmartphone = listOf(90, 100, 110, 130, 150, 170, 190, 180, 160, 140, 120, 100) val salesTablet = listOf(60, 70, 80, 90, 100, 110, 120, 110, 100, 90, 80, 70) // A data frame with columns for Month, Sales, and Product val dfSales = dataFrameOf( "Month" to months + months + months, "Sales" to salesLaptop + salesSmartphone + salesTablet, "Product" to List(12) { "Laptop" } + List(12) { "Smartphone" } + List(12) { "Tablet" }, )このデータフレームは
dataFrameOf()関数を使用し、12ヶ月間に販売された製品(ラップトップ、スマートフォン、タブレット)の数を含んでいます。フレーム内のデータを探索します。例えば、最も売上が高かった製品と月を見つけることができます。
nonedfSales.maxBy("Sales")
データフレームをCSVファイルとしてエクスポートすることもできます。
kotlin// Export your data to CSV format dfSales.writeCSV("sales-stats.csv")
チャート
Kotlin Notebookで直接様々なチャートを作成し、データを可視化できます。
ノートブックにKandyプロットライブラリを追加します。
none%use kandy同じデータフレームを使用し、新しいセルで
plot()関数を実行します。kotlinval salesPlot = dfSales.groupBy { Product }.plot { bars { // Access the data frame's columns used for the X and Y axes x(Month) y(Sales) // Access the data frame's column used for categories and sets colors for these categories fillColor(Product) { scale = categorical( "Laptop" to Color.PURPLE, "Smartphone" to Color.ORANGE, "Tablet" to Color.GREEN ) legend.name = "Product types" } } // Customize the chart's appearance layout.size = 1000 to 450 layout.title = "Yearly Gadget Sales Results" } salesPlot
プロットを
.png、jpeg、.html、または.svg形式でエクスポートすることもできます。kotlin// Specify the output format for the plot file: salesPlot.save("sales-chart.svg")
