How to get a legend with a title in the right bottom corner

To a given graph I want to add a legend in the right bottom corner like this:

Having read this thread I tried the following:

digraph with_legend {
    rankdir=LR
    {
	    node [shape=box style=rounded]
        A B C D
    }

    A -> B -> C -> D -> A

    graph [labelloc="b" labeljust="r" label="Legend"] {
        dummy [shape=none label=<
	<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
	<TR><TD>left 1</TD><TD>right 1</TD></TR>
	<TR><TD>left 2</TD><TD>right 2</TD></TR>	</TABLE>>]
    }
}

but somehow the table label does not want to stay with the (ok positioned) legend title:

Any idea how to tell the table label to be positioned under the title “Legend”?

Even though it looks like you have combined the word Legend and the HTML table into one unit, looks can be deceiving. They are two distinct things in the “eyes” of Graphviz. Best way to see what Graphviz thinks you want is dot -Tcanon myfile.gv

OK, here is one way to get the legend table positioned under the word Legend - add the word to the table:

digraph with_legend {
    rankdir=LR
    {
	    node [shape=box style=rounded]
        A B C D
    }

    A -> B -> C -> D -> A

    graph [labelloc="b" labeljust="r" label=<
	<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
	<TR><TD COLSPAN="2" SIDES="b">Legend</TD></TR>
	<TR><TD>left 1</TD><TD>right 1</TD></TR>
	<TR><TD>left 2</TD><TD>right 2</TD></TR>
	</TABLE>>]
}

Giving:
combineLegend1

1 Like

Works pretty well. Thanks.

The whole method feels a bit cumbersome though. I’m not sure whether GraphViz is the best tool to add a legend to a graph: Maybe some SVG composer language exists? Or postprocessing with ImageMagick would be more suitable to have more fine-grained control?

In my current use case I am going with the HTML-like label in Graphviz for the legend, because it’s good enough. :slight_smile:

Thanks again!

A different method:
A (Linux) shell script that creates two graphs:

  • the “real” graph
  • the Legend

It then runs dot on both and finally uses convert (ImageMagick) to combine the two.

cat > /tmp/oo1.gv <<EOF
digraph without_legend {
    rankdir=LR
    {
	    node [shape=box style=rounded]
        A B C D
    }

    A -> B -> C -> D -> A
}
EOF
cat > /tmp/oo2.gv <<EOF
digraph L{
  graph [label=Legend labelloc=t]
  mylegend [shape=plain labelloc="b" labeljust="r" label=<
	<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
	<TR><TD>left 1</TD><TD>right 1</TD></TR>
	<TR><TD>left 2</TD><TD>right 2</TD></TR>
	</TABLE>>]
}
EOF

dot -Tpng /tmp/oo1.gv >/tmp/oo1.png
dot -Tpng /tmp/oo2.gv >/tmp/oo2.png
convert -gravity east -append /tmp/oo[12].png /tmp/o.png

Giving:
o

1 Like