在GraphViz文件中,具有相同属性的节点组

15
GraphVizdot语言中,我想描述一个二元网络。因此,我有两种不同类型的节点。例如,一组可以包括阅读者,而另一组可以包括被阅读的书籍。
我想给这两组节点不同的外观(如shapecolor等)。我应该如何在一条语句中指定一组节点的属性,以便能够在一个地方更改每组节点的外观,而不是在所有单个节点描述中进行更改?
这可以通过类似于属性继承的方式来实现,但我不知道dot语言是否具有这个概念。
2个回答

24

原则上有三种可能性:

  1. 在创建节点之前设置默认属性:
    • 全局范围内 - 对所有后续的节点创建有效
    • 在子图中局部范围内 - 仅对子图内的节点创建有效
  2. 使用显式属性创建节点
  3. 在创建后将属性分配给一组节点。

选项1和2仅允许每个节点一个组,因为创建是单个事件。选项3允许每个赋值不同的分组。


在创建节点之前全局设置默认属性

digraph {
  x // node with current defaults

  // set default
  node [shape=box color=red]
  // create with default values
  a1, a2

  // set default
  node [shape=circle color=blue]
  // create with default values
  b1, b2

  y // node with current defaults

  x->{a1 a2}
  a1->{b1 b2}
  a2->{b1 b2}
  {b1,b2}->y
}

在创建节点之前本地设置默认属性

digraph {
  x // node with current defaults

  {
      // set default
      node [shape=box color=red]
      // create with default values
      a1, a2
  }

  {
      // set default
      node [shape=circle color=blue]
      // create with default values
      b1, b2
  }

  y // node with current defaults

  x->{a1 a2}
  a1->{b1 b2}
  a2->{b1 b2}
  {b1,b2}->y
}

在这里输入图片描述


创建带有显式属性的节点

digraph {
  x // node with current defaults

  // create with explicit attributes
  a1, a2 [shape=box color=red]

  // create with explicit attributes
  b1, b2 [shape=circle color=blue]

  y // node with current defaults

  x->{a1 a2}
  a1->{b1 b2}
  a2->{b1 b2}
  {b1,b2}->y
}

创建后给一组节点分配属性

digraph {
  x // node with current defaults

  // create with default values
  a1, a2, b1, b2

  // assign shape
  a1, a2 [shape=box]
  b1, b2 [shape=circle]

  // assign color
  a1, b2 [color=red]
  b1, a2 [color=blue]

  y // node with current defaults

  x->{a1 a2}
  a1->{b1 b2}
  a2->{b1 b2}
  {b1,b2}->y
}

在此输入图片描述


2
哇,这非常全面。谢谢! - halloleo
@stefan 为什么我在 https://graphviz.org/doc/info/lang.html 上找不到 a1, a2 [atrrbuites...] 对应的点语言语法? - sify

6
可以使用node关键字针对图中的所有节点进行操作,或者使用edge关键字针对图中的所有边进行操作。也可以逐个节点或逐条边地进行操作。 整个图或子图的示例:
digraph
{
  subgraph readers
  {
      node[shape=box; color=red;]
      r1; r2; r3;
  }

  subgraph books
  {
      node[shape=circle; color=blue;]
      b1; b2; b3;
  }
  r1->{b1 b2}
  r2->{b2 b3}
  r3->{b1 b2 b3}
}

这将为您提供以下图表: enter image description here 每个节点属性的示例:
digraph
{
    n1[shape=triangle];
    n2[shape=star];
    n3[shape=square];

    n1->n2->n3
}

将会给出以下图表:

enter image description here


非常感谢。我需要的是“子图”概念。 - halloleo
2
谢谢,这也帮助了我。最初让我困惑的是,在创建节点之后,我添加了指定属性的子图。节点需要在子图中创建才能接收到这些属性。 - maccaroo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接