0
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.

Ruby-Graphviz でサブグラフを描く

Posted at

ゴール

Ruby-Graphvizサブグラフ を描きたい

まずは、dot 言語で書いてみる

Graphviz 解説記事を参考にして

digraph node_sample {
...
  subgraph cluster_1 {
    label = "clu1";
    labelloc = "t";
    labeljust = "l";
    fillcolor = "#888888";

    nu [label = "nu", shape = "trapezium"];
    xi [label = "xi", shape = "trapezium"];

    nu -> xi;

    subgraph cluster_2 {
      label = "clu2";
      labelloc = "t";
      labeljust = "l";
      fillcolor = "#888888";

      nu2 [label = "nu2", shape = "trapezium"];
      xi2 [label = "xi2", shape = "trapezium"];

      nu2 -> xi2;

     subgraph cluster_3 {
        label = "clu3";
        labelloc = "t";
        labeljust = "l";
        fillcolor = "#888888";

        nu3 [label = "nu3", shape = "trapezium"];
        xi3 [label = "xi3", shape = "trapezium"];

        nu3 -> xi3;
      }
    }

    nu -> nu2
  }
}

dot -T png sample.dot -o sample.png して open sample.png すると

20220325153803.png

次に、Gem で書いてみる

require 'ruby-graphviz'

# Create a new graph
g = GraphViz::new(:G, type: :digraph, use: :dot, rotate: 0, rankdir: :LR)

# setting sub-graph
g.add_graph('cluster_1', label: "clu1", labelloc: "t", labeljust: "l", fillcolor: "#888888")
sub1 = g.get_graph('cluster_1')
hello1 = sub1.add_nodes( "Hello1" )
world1 = sub1.add_nodes( "World1" )
sub1.add_edges( hello1, world1 )

sub1.add_graph('cluster_2', label: "clu2", labelloc: "t", labeljust: "l", fillcolor: "#888888")
sub2 = sub1.get_graph('cluster_2')
hello2 = sub2.add_nodes( "Hello2" )
world2 = sub2.add_nodes( "World2" )
sub2.add_edges( hello2, world2 )

sub1.add_edges( hello1, world2 )

# Generate output image
g.output( :png => "./tmp/hello_world.png" )

ポイントとしては、add_graph を使う際、第一引数として渡すグラフ名を cluster から始まる文字列にすること(そうしないとサブグラフとして機能しない)

20220325154111.png

0
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
0
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?