LoginSignup
1
0

wslでelixir その140

Last updated at Posted at 2024-02-21

概要

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

練習問題

Livebookで、Qiita APIでフォロワー求めて、d3.jsのclusterで表示せよ。

写真

clu.png

セットアップ

Mix.install([
  {:jason, "~> 1.4"},
  {:req, "~> 0.4.5"},
  {:timex, "~> 3.7"},
  {:vega_lite, "~> 0.1.6"},
  {:kino, "~> 0.8.1"},
  {:kino_vega_lite, "~> 0.1.7"},
  {:explorer, "~> 0.5.6"},
  {:kino_explorer, "~> 0.1.4"},
  {:nx, "~> 0.5"}
])

サンプルコード

ids =
  "https://qiita.com/api/v2/users/ohisama@github/followers?page=1&per_page=80"
  |> Req.get!(headers: [{"Authorization", "Bearer ***"}])
  |> Map.get(:body)
  |> Enum.map(&Map.take(&1, ["id"]))

idl =
  Enum.map(ids, fn x ->
    %{name: x["id"]}
  end)

chc = %{
  "children" => idl,
  "name" => "ohisama"
}

defmodule KinoD3.Cluster 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);
       var cluster = d3.cluster().size([250, 250])
       cluster(root);
       var g = d3.select('#out')
          .append("svg").attr("width", 800).attr("height", 800)
          .append("g").attr("transform", "translate(400, 300)");

       var link = g.selectAll(".link").data(root.links()).enter().append("path")
        .attr("class", "link").attr("fill", "none").attr("stroke", "#555")
        .attr("stroke-width", "1.5px").attr("opacity", "0.6")
        .attr("d", d3.linkRadial().angle(function(d) {
      		return (d.x + 90) * Math.PI / 180;
      	}).radius(function(d) {
      		return d.y;
      }));
     	var node = g.selectAll(".node").data(root.descendants()).enter().append("g")
          .attr("transform", function(d) {
       	return "rotate(" + (d.x) + ")translate(" + d.y + ")";
       })
       node.append("circle").attr("r", 8).attr("stroke", "steelblue")
          .attr("stroke-width", "1.5px").attr("fill", "white");
      	node.append("text").attr("dy", 3).attr("dx", function(d) {
      		return d.x < 90 || d.x > 270 ? 8 : -8;
      	}).style("text-anchor", function(d) {
       	return d.x < 90 || d.x > 270 ? "start" : "end";
      	}).attr("font-size", "150%").attr("transform", function(d) {
      		return d.x < 90 || d.x > 270 ? null : "rotate(180)";
      	}).text(function(d) {
       	return d.data.name;
       });
    }
    """
  end
end

chc
|> Jason.encode!()
|> KinoD3.Cluster.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