在 Scala 筆記本中顯示 HTML、SVG 和 D3 視覺化

在本教學中,您會使用 displayHTML 函式,在 Azure Databricks Scala 筆記本中轉譯 HTML、SVG 和 D3 視覺化內容。

Note

  • 筆記本儲存格(包含內容與輸出)的最大容量為 16MB。 請確定您傳遞給 displayHTML 函數的 HTML 大小不會超過此值。
  • 連結外部資源時,請使用 https://http://。 否則,圖像、圖片或JavaScript可能因混合內容錯誤而無法正確呈現。

先決條件

  • 存取 Azure Databricks 工作區。
  • 一台連接至運算資源的筆記型電腦。

顯示 HTML 程式碼

displayHTML("<h3>You can view HTML code in notebooks.</h3>")

顯示 SVG 視覺化

displayHTML("""<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg>""")

使用 displayHTML 顯示 D3 視覺化

你可以從 Scala 的資料結構動態產生 D3 視覺化 HTML。

想了解更多關於D3的資訊,請見 https://d3js.org/。

// Change these colors to your favorites to change the D3 visualization.
val colors = Array((197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 244, 239), (247, 247, 247), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33))

displayHTML(s"""
<!DOCTYPE html>
<meta charset="utf-8">
<style>

path {
  fill: yellow;
  stroke: #000;
}

circle {
  fill: #fff;
  stroke: #000;
  pointer-events: none;
}

.PiYG .q0-9{fill:rgb${colors(0)}}
.PiYG .q1-9{fill:rgb${colors(1)}}
.PiYG .q2-9{fill:rgb${colors(2)}}
.PiYG .q3-9{fill:rgb${colors(3)}}
.PiYG .q4-9{fill:rgb${colors(4)}}
.PiYG .q5-9{fill:rgb${colors(5)}}
.PiYG .q6-9{fill:rgb${colors(6)}}
.PiYG .q7-9{fill:rgb${colors(7)}}
.PiYG .q8-9{fill:rgb${colors(8)}}

</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>

var width = 960,
    height = 500;

var vertices = d3.range(100).map(function(d) {
  return [Math.random() * width, Math.random() * height];
});

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("class", "PiYG")
    .on("mousemove", function() { vertices[0] = d3.mouse(this); redraw(); });

var path = svg.append("g").selectAll("path");

svg.selectAll("circle")
    .data(vertices.slice(1))
  .enter().append("circle")
    .attr("transform", function(d) { return "translate(" + d + ")"; })
    .attr("r", 2);

redraw();

function redraw() {
  path = path.data(d3.geom.delaunay(vertices).map(function(d) { return "M" + d.join("L") + "Z"; }), String);
  path.exit().remove();
  path.enter().append("path").attr("class", function(d, i) { return "q" + (i % 9) + "-9"; }).attr("d", String);
}

</script>
  """)

下一步

範例筆記本

在 Scala 筆記本中顯示 HTML、SVG 和 D3 視覺化

拿筆記本