1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

wslでelixir その110

Last updated at Posted at 2023-11-30

概要

wsl(wsl2じゃない)で、elixirやってみた。
練習問題、やってみた。

練習問題

Livebookでd3のtreemapを、Mapから作れ。

写真

image.png

サンプルコード

defmodule KinoD3.Treemap do
  use Kino.JS

  def new(html) do
    Kino.JS.new(__MODULE__, html)
  end

  asset "main.js" do
    """
    import "https://d3js.org/d3.v5.min.js";
    export function init(ctx, json) {
      const chartid = document.createElement("div");
    	chartid.id = "out";
    	ctx.root.appendChild(chartid);
    	var obj = JSON.parse(json); 
      var root = d3.hierarchy(obj);
      root.sum(function(d) { 
        return d.value; 
      }).sort(function(a, b) { 
        return b.height - a.height || b.value - a.value; 
      }); 
      var treemap = d3.treemap().size([500, 500]).padding(1).round(true);
      treemap(root);
      var g = d3.select('#out')
        .append("svg").attr("width", 600).attr("height", 600)
        .selectAll(".node").data(root.leaves()).enter().append("g").attr("class", "node")
        .attr("transform", function(d) { 
          return "translate(" + d.x0 + "," + (d.y0) + ")"; 
        });
      g.append("rect").style("width", function(d) { 
        return d.x1 - d.x0; 
      }).style("height", function(d) { 
        return d.y1 - d.y0; 
      }).style("fill", function(d) {
        while(d.depth > 1) d = d.parent;
        return d3.schemeCategory10[parseInt(d.value % 7)];
      }).style("opacity", 0.6)
      g.append("text").attr("text-anchor", "start").attr("x", 5).attr("dy", 30)
        .attr("font-size", "150%").attr("class", "node-label").text(function(d) { 
          return d.data.name + " : " + d.value; 
        });
    }
    """
  end
end

%{
  "children" => [
    %{"name" => "B", "value" => 25},
    %{
      "children" => [
        %{"name" => "D", "value" => 10},
        %{"name" => "E", "value" => 15},
        %{"name" => "F", "value" => 10}
      ],
      "name" => "C"
    },
    %{"name" => "G", "value" => 15},
    %{
      "children" => [
        %{"name" => "I", "value" => 20},
        %{"name" => "J", "value" => 10}
      ],
      "name" => "H"
    },
    %{"name" => "K", "value" => 10}
  ],
  "name" => "A"
}
|> Jason.encode!()
|> KinoD3.Treemap.new()

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?