How to set the width and heigth of the ouput image in Pygraphviz

Question:

I am creating a .png file like this:

import pygraphviz as pgv
G = pgv.AGraph()
G.add_nodes("a")
G.add_edge("b", "c")

G.layout()
G.draw("output.png")

How can I set the size of the output image?

Asked By: jbochi

||

Answers:

You can set the maximum size of your output image, by setting size, which is an attribute of the graph object. E.g.,

digraph "my_graph" {

     graph[ fontname = "Helvetica-Oblique",
            fontsize = 12,
            label = "some label",
            size = "7.75,10.25" ];

     node [ shape = polygon,
            sides = 4 ];
}

In this example, i’ve set the graph size to 7.75 x 10.25, which is the size you want, to ensure that your graph fits on an 8.5 x 11 inch sheet and also to ensure that it occupies all of the space on that sheet.

Answered By: doug

In addition to setting the size, you might want to enforce a particular aspect ratio too.

To set a ratio of 1:1.4 (width=1, height=1.4, i.e. that of an A4 page, approximately), you can do this (with a maximum dimension of 10 inches):

G.draw('output.png', args='-Gsize=10 -Gratio=1.4', prog='dot')

The format here is:

Graph arguments: -G<arg>; Node arguments: -N<arg>; Edge arguments: -E<arg>.

There’s a list of arguments here:
https://manpages.debian.org/stretch/graphviz/dot.1.en.html

Hope that helps.

Answered By: Chris

You can easily set up the resolution with :

G.draw("file.png", args='-Gdpi=200', prog="dot")

Or since it’s a graph attribute :

G.graph_attr['dpi'] = '200'

If you wish to avoid concerns regarding resolution, an alternative option is to export the file in a vector format such as .svg.

Answered By: Arthur R.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.