3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Elixirでグラフを描く〜VegaLite〜

Last updated at Posted at 2024-09-13

今回の目標

  • 折れ線グラフと棒グラフを同時表示
    • layersを使う
    • 色も変更する
  • y軸は1〜100のランダムの数値を使う
  • png形式で保存する

環境作成

$ sudo npm install -g vega vega-lite canvas

Export.to_pngの時に必要でした

プロジェクト作成

$ mix new vegalite_experiment 
$ cd vegalite_experiment

VegaLite組み込み

mix.exs
# 〜省略〜
  defp deps do
    [
+     {:vega_lite, "~> 0.1.9"},
+     {:jason, "~> 1.2"}
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end
# 〜省略〜
$ mix deps.get

検証ソース

lib/vegalite_experiment.ex
defmodule VegaliteExperiment do
  @moduledoc """
  Documentation for `VegaliteExperiment`.
  """
  alias VegaLite, as: Vl

  @doc """
  Hello world.

  ## Examples

      iex> VegaliteExperiment.hello()
      :world

  """

  def hello do
    y = for _ <- 1..20, do: Enum.random(1..100)

    Vl.new(width: 800, height: 400)
    |> Vl.data_from_values(x: 1..20, y: y)
    |> Vl.layers([
      Vl.new()
      |> Vl.mark(:bar, color: "#ffaaaa", width: 20)
      |> Vl.encode_field(:x, "x", type: :quantitative)
      |> Vl.encode_field(:y, "y", type: :quantitative),
      Vl.new()
      |> Vl.mark(:line, color: "#aaaaff")
      |> Vl.encode_field(:x, "x", type: :quantitative)
      |> Vl.encode_field(:y, "y", type: :quantitative)
    ])
    |> Vl.Export.to_png()
    |> then(&File.write!("test.png", &1))

    :world
  end
end

実行

$ mix run -e "VegaliteExperiment.hello()"

test.pngができました

image.png

ソース(github)

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?