How to use the graphviz.Graph function in graphviz

To help you get started, we’ve selected a few graphviz examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github EntilZha / pygraph / pygraph / cli.py View on Github external
def main(engine, undirected, format, name, dot, file, edges, no_vertex_labels):
    if undirected:
        graph = graphviz.Graph(engine=engine, format=format)
    else:
        graph = graphviz.Digraph(engine=engine, format=format)
    if name:
        graph.body.append(r'label = "{0}"'.format(name))
    edges = seq(edges).map(split_edge)

    if no_vertex_labels:
        edges.map(lambda e: (e.left, e.right)).flatten().distinct()\
            .filter_not(lambda n: n is None).for_each(lambda n: graph.node(n, label=''))
    else:
        edges.map(lambda e: (e.left, e.right)).flatten().distinct() \
            .filter_not(lambda n: n is None).for_each(lambda n: graph.node(n))

    edges.filter(lambda e: e.right is not None) \
        .for_each(lambda e: graph.edge(e.left, e.right, label=e.label))
    filepath, filename = path.split(file)
github OpenSourceEconomics / econ-project-templates / {{cookiecutter.project_slug}} / src_stata / final / project_dependency_graph.py View on Github external
import functools
from pathlib import Path

import graphviz as gv
from waflib import Utils


graph = functools.partial(gv.Graph, format="png")
digraph = functools.partial(gv.Digraph, format="png")

styles = {
    "graph": {
        "label": "DAG of Project",
        "fontsize": "48",
        "fontcolor": "white",
        "bgcolor": "#333333",
        "rankdir": "LR",
    },
    "nodes": {
        "fontname": "Helvetica",
        "shape": "hexagon",
        "fontcolor": "white",
        "color": "white",
        "style": "filled",
github jakubjafra / stellaris-map-generation / utils / star-graph / json2graph.py View on Github external
def execute(sourcepath, outputpath):
    stars_file = open('{}/basics.json'.format(sourcepath))
    data = json.loads(stars_file.read())
    stars_file.close()

    dot = Graph(strict='true')
    generate_all_stars(dot, data)
    dot.render('{}/all-stars.dot'.format(outputpath))

    dot = Graph(strict='true')
    generate_sectors(dot, data)
    dot.render('{}/sectors.dot'.format(outputpath))

    dot = Graph(strict='true')
    generate_empires(dot, data)
    dot.render('{}/empires.dot'.format(outputpath))

    dot = Graph(strict='true')
    generate_dependencies(dot, data)
    dot.render('{}/independencies.dot'.format(outputpath))

    dot = Graph(strict='true')
    generate_hyperlanes_graph(dot, data)
    dot.render('{}/hyperlanes.dot'.format(outputpath))
github pyta-uoft / pyta / sample_usage / draw_tnodes.py View on Github external
def gen_graph_from_nodes(nodes, type_fail=None):
    graph = Graph(format='png', strict=True)
    graph.node_attr['fontname'] = 'Courier New'
    graph.edge_attr['fontname'] = 'Courier New'
    for node in nodes:
        graph.node(_type_str(node.type),
                   '{type: %s|ast_node: %s|parent\'s type: %s}' %
                   (_type_str(node.type),
                    node.ast_node.as_string().replace('<', '\\<').replace('>', '\\>')
                        if node.ast_node else 'None',
                    _type_str(node.parent.type) if node.parent else 'NA'),
                   shape='record', style='rounded')
        for neighb, ctx_node in node.adj_list:
            graph.edge(_type_str(node.type), _type_str(neighb.type),
                       label=(f' {ctx_node.as_string()}' if ctx_node else ''))
    if type_fail:
        graph.node('tf',
                   '{TypeFail|src_node: %s}' %
github gil9red / SimplePyScripts / graph__networkx__d3__dot_graphviz / graphviz__examples / diff_between_Digraph_and_Graph.py View on Github external
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'


# pip install graphviz
from graphviz import Digraph, Graph

# Directed graph
g = Digraph('G', filename='test-output/hello_Digraph.gv')
g.edge('Hello', 'World')
g.view(cleanup=True)

g = Graph('G', filename='test-output/hello_Graph.gv')
g.edge('Hello', 'World')
g.view(cleanup=True)
github natenka / pyneng-examples-exercises / exercises / 25_oop_basics / draw_network_graph.py View on Github external
def draw_topology(topology_dict, dest_filename="img/topology"):
    """
    topology_dict - словарь с описанием топологии
    Этот словарь
        {('R4', 'Fa0/1'): ('R5', 'Fa0/1'),
         ('R4', 'Fa0/2'): ('R6', 'Fa0/0')}
    соответствует топологии:
    [ R5 ]-Fa0/1 --- Fa0/1-[ R4 ]-Fa0/2---Fa0/0-[ R6 ]
    Функция генерирует топологию, в формате svg.
    И записывает файл topology.svg в каталог img.
    """
    nodes = set(
        [item[0] for item in list(topology_dict.keys()) + list(topology_dict.values())]
    )

    g1 = gv.Graph(format="svg")

    for node in nodes:
        g1.node(node)

    for key, value in topology_dict.items():
        head, t_label = key
        tail, h_label = value
        g1.edge(head, tail, headlabel=h_label, taillabel=t_label, label=" " * 12)

    g1 = apply_styles(g1, styles)
    filename = g1.render(filename=dest_filename)
    print("Graph saved in", dest_filename)
github netbox-community / netbox / netbox / extras / models.py View on Github external
def render(self, img_format='png'):

        from dcim.models import Device

        # Construct the graph
        if self.type == TOPOLOGYMAP_TYPE_NETWORK:
            G = graphviz.Graph
        else:
            G = graphviz.Digraph
        self.graph = G()
        self.graph.graph_attr['ranksep'] = '1'
        seen = set()
        for i, device_set in enumerate(self.device_sets):

            subgraph = G(name='sg{}'.format(i))
            subgraph.graph_attr['rank'] = 'same'
            subgraph.graph_attr['directed'] = 'true'

            # Add a pseudonode for each device_set to enforce hierarchical layout
            subgraph.node('set{}'.format(i), label='', shape='none', width='0')
            if i:
                self.graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
github brooksandrew / postman_problems / postman_problems / viz.py View on Github external
"""
    Convert a networkx Multigraph to a graphviz.dot.Graph
    This allows us to modify the graphviz graph programmatically in Python before we dump to dot format and plot.
    Note the Graphviz plot is created sequentially... It is hard to edit it after the edges and node attrs are written.

    Args:
        graph (networkx graph): networkx graph to be converted to dot notation
        directed (boolean): is `graph` directed... more specifically, do we want the returned graph to be directed?

    Returns:
        graphviz.dot.Graph: conversion of `graph` to a graphviz dot object.
    """
    if directed:
        G = gv.Digraph()
    else:
        G = gv.Graph()

    # add nodes and their attributes to graphviz object
    for n in graph.nodes():
        n_attr = {k: str(v) for k, v in graph.node[n].items()}
        G.attr('node', n_attr)
        G.node(str(n), str(n))

    # add edges and their attributes to graphviz object
    for e in graph.edges(keys=True):
        e_attr = {k: str(v) for k, v in graph[e[0]][e[1]][e[2]].items()}
        G.edge(str(e[0]), str(e[1]), **e_attr)

    return G
github streamlit / streamlit / e2e / scripts / graphviz_chart.py View on Github external
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit as st

import graphviz as graphviz

# basic graph
hello = graphviz.Digraph("Hello World")
hello.edge("Hello", "World")

# styled graph
styled = graphviz.Graph("G", filename="g_c_n.gv")
styled.attr(bgcolor="purple:pink", label="agraph", fontcolor="white")

with styled.subgraph(name="cluster1") as c:
    c.attr(
        fillcolor="blue:cyan",
        label="acluster",
        fontcolor="white",
        style="filled",
        gradientangle="270",
    )
    c.attr(
        "node", shape="box", fillcolor="red:yellow", style="filled", gradientangle="90"
    )
    c.node("anode")

# complex graph
github NervanaSystems / ngraph-neon / ununoctium / geon / util / analysis.py View on Github external
def _graphviz(self, name=''):
        from graphviz import Graph
        dot = Graph()
        processed = set()
        for na, _ in list(self.neighbors.items()):
            dot.node(na.id, na.graph_label, na.style)
            for nb in _:
                dot.node(nb.id, nb.graph_label, nb.style)
                if (nb, na) not in processed:
                    dot.edge(na.id, nb.id)
                    processed.add((na, nb))
        return dot