Draw a networkx graph with Pygraphviz.
770774
def draw_graph(G: nx.DiGraph, filename: str):
    
    A = to_agraph(G)
    A.graph_attr["rankdir"] = "LR"
    A.draw(filename, prog="dot")
1226327
def draw(self):
        
        self.update_all()
        self.vertex_list.draw(self.gl)
        pyglet.gl.glLoadIdentity()
307721
def to_networkx(self, labels=None, edge_labels=False):
        
        import networkx as nx
        graph = nx.DiGraph()
        for node in self._traverse_nodes():
            u = node.key
            graph.add_node(u)  # Minor redundancy
            # Set node properties
            graph.nodes[u]['value'] = node.value
            if labels is not None:
                label = ','.join([str(getattr(node, k)) for k in labels])
                graph.nodes[u]['label'] = label
            if node.left is not None:
                v = node.left.key
                graph.add_node(v)
                graph.add_edge(u, v)
                if edge_labels:
                    graph.edge[u][v]['label'] = 'L'
            if node.right is not None:
                v = node.right.key
                graph.add_node(v)
                graph.add_edge(u, v)
                if edge_labels:
                    graph.edge[u][v]['label'] = 'R'
        return graph
716458
def get_nx_graph(ea):
    """"""
    nx_graph = networkx.DiGraph()
    func = idaapi.get_func(ea)
    flowchart = FlowChart(func)
    for block in flowchart:
        # Make sure all nodes are added (including edge-less nodes)
        nx_graph.add_node(block.startEA)

        for pred in block.preds():
            nx_graph.add_edge(pred.startEA, block.startEA)
        for succ in block.succs():
            nx_graph.add_edge(block.startEA, succ.startEA)

    return nx_graph
595969
def to_networkx(graph):
    

    # import here so networkx is not always required.
    import networkx as nx

    nodes = graph["nodes"].keys()
    edges = [[start, end] for start, ends in graph["links"].items() for end in ends]

    g = nx.Graph()
    g.add_nodes_from(nodes)
    nx.set_node_attributes(g, dict(graph["nodes"]), "membership")

    g.add_edges_from(edges)

    return g
81512
def as_graph(self) -> Graph:  # pragma: no cover
        """"""
        if Graph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Graph()
        nodes_left = {}  # type: Dict[TLeft, str]
        nodes_right = {}  # type: Dict[TRight, str]
        node_id = 0
        for (left, right), value in self._edges.items():
            if left not in nodes_left:
                name = 'node{:d}'.format(node_id)
                nodes_left[left] = name
                graph.node(name, label=str(left))
                node_id += 1
            if right not in nodes_right:
                name = 'node{:d}'.format(node_id)
                nodes_right[right] = name
                graph.node(name, label=str(right))
                node_id += 1
            edge_label = value is not True and str(value) or ''
            graph.edge(nodes_left[left], nodes_right[right], edge_label)
        return graph
890714
def _to_graphviz(tree_info, show_info, feature_names, precision=None, **kwargs):
    
    if GRAPHVIZ_INSTALLED:
        from graphviz import Digraph
    else:
        raise ImportError('You must install graphviz to plot tree.')

    def add(root, parent=None, decision=None):
        """Recursively add node or edge."""
        if 'split_index' in root:  # non-leaf
            name = 'split{0}'.format(root['split_index'])
            if feature_names is not None:
                label = 'split_feature_name: {0}'.format(feature_names[root['split_feature']])
            else:
                label = 'split_feature_index: {0}'.format(root['split_feature'])
            label += r'\nthreshold: {0}'.format(_float2str(root['threshold'], precision))
            for info in show_info:
                if info in {'split_gain', 'internal_value'}:
                    label += r'\n{0}: {1}'.format(info, _float2str(root[info], precision))
                elif info == 'internal_count':
                    label += r'\n{0}: {1}'.format(info, root[info])
            graph.node(name, label=label)
            if root['decision_type'] == '<=':
                l_dec, r_dec = '<=', '>'
            elif root['decision_type'] == '==':
                l_dec, r_dec = 'is', "isn't"
            else:
                raise ValueError('Invalid decision type in tree model.')
            add(root['left_child'], name, l_dec)
            add(root['right_child'], name, r_dec)
        else:  # leaf
            name = 'leaf{0}'.format(root['leaf_index'])
            label = 'leaf_index: {0}'.format(root['leaf_index'])
            label += r'\nleaf_value: {0}'.format(_float2str(root['leaf_value'], precision))
            if 'leaf_count' in show_info:
                label += r'\nleaf_count: {0}'.format(root['leaf_count'])
            graph.node(name, label=label)
        if parent is not None:
            graph.edge(parent, name, decision)

    graph = Digraph(**kwargs)
    add(tree_info['tree_structure'])

    return graph
326861
def as_graph(self) -> Digraph:  # pragma: no cover
        """"""
        if Digraph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        dot = Digraph()

        nodes = set()
        queue = [self._root]
        while queue:
            state = queue.pop(0)
            if not state.payload:
                dot.node('n{!s}'.format(state.id), '', {'shape': ('circle' if state else 'doublecircle')})
            else:
                dot.node('n{!s}'.format(state.id), '\n'.join(map(str, state.payload)), {'shape': 'box'})

            for next_state in state.values():
                if next_state.id not in nodes:
                    queue.append(next_state)
                    nodes.add(state.id)

        nodes = set()
        queue = [self._root]
        while queue:
            state = queue.pop(0)
            if state.id in nodes:
                continue
            nodes.add(state.id)

            for (label, other) in state.items():
                dot.edge('n{!s}'.format(state.id), 'n{!s}'.format(other.id), _term_str(label))
                if other.id not in nodes:
                    queue.append(other)

        return dot
238925
def dict_to_nx(graph, oriented=False):
    """"""
    nxg = nx.DiGraph() if oriented else nx.Graph()
    for node, succs in graph.items():
        for succ in succs:
            nxg.add_edge(node, succ)
    return nxg
1320456
def draw_nodes(self):
        
        node_r = self.node_sizes
        for i, node in enumerate(self.nodes):
            x = self.node_coords["x"][i]
            y = self.node_coords["y"][i]
            color = self.node_colors[i]
            node_patch = patches.Ellipse(
                (x, y), node_r[i], node_r[i], lw=0, color=color, zorder=2
            )
            self.ax.add_patch(node_patch)
149305
def draw(self, y, **kwargs):
        

        # draw the histogram
        hist, bin_edges = np.histogram(y, bins=self.bins)
        self.bin_edges_ = bin_edges
        self.ax.hist(y, bins=self.bins, color=kwargs.pop("color", "#6897bb"), **kwargs)

        # add vetical line with binning reference values
        plt.vlines(bin_edges,0,max(hist),colors=kwargs.pop("colors", "r"))
673378
def draw_nodes(self):
        
        node_r = self.nodeprops["radius"]
        lw = self.nodeprops["linewidth"]
        for i, node in enumerate(self.nodes):
            x = self.node_coords["x"][i]
            y = self.node_coords["y"][i]
            color = self.node_colors[i]
            node_patch = patches.Circle(
                (x, y), node_r, lw=lw, color=color, zorder=2
            )
            self.ax.add_patch(node_patch)
            if self.node_labels:
                label_x = self.node_label_coords["x"][i]
                label_y = self.node_label_coords["y"][i]
                label_tx = self.node_label_coords["tx"][i]
                label_ty = self.node_label_coords["ty"][i]
                label_ha = self.node_label_aligns["has"][i]
                label_va = self.node_label_aligns["vas"][i]

                # ----- Node label rotation layout -----

                if self.node_label_layout == "rotation":
                    rot = self.node_label_rotation[i]

                    self.ax.text(
                        s=node,
                        x=label_x,
                        y=label_y,
                        ha=label_ha,
                        va=label_va,
                        rotation=rot,
                        rotation_mode="anchor",
                        color=self.node_label_color[i],
                        fontsize=self.fontsize,
                        family=self.fontfamily,
                    )

                # ----- Node label numbering layout -----

                elif self.node_label_layout == "numbers":

                    # Draw descriptions for labels
                    desc = "%s - %s" % ((i, node) if (x > 0) else (node, i))
                    self.ax.text(
                        s=desc,
                        x=label_tx,
                        y=label_ty,
                        ha=label_ha,
                        va=label_va,
                        color=self.node_label_color[i],
                        fontsize=self.fontsize,
                        family=self.fontfamily,
                    )

                    # Add numbers to nodes
                    self.ax.text(
                        s=i, x=label_x, y=label_y, ha="center", va="center"
                    )

                # Standard node label layout
                else:

                    # Draw node text straight from the nodes
                    self.ax.text(
                        s=node,
                        x=label_x,
                        y=label_y,
                        ha=label_ha,
                        va=label_va,
                        color=self.node_label_color[i],
                        fontsize=self.fontsize,
                        family=self.fontfamily,
                    )
1093174
def draw_patch(self, ax, patch, force_trans=None):
        """"""
        vertices, pathcodes = utils.SVG_path(patch.get_path())
        transform = patch.get_transform()
        coordinates, vertices = self.process_transform(transform,
                                                       ax, vertices,
                                                       force_trans=force_trans)
        linestyle = utils.get_path_style(patch, fill=patch.get_fill())
        self.renderer.draw_path(data=vertices,
                                coordinates=coordinates,
                                pathcodes=pathcodes,
                                style=linestyle,
                                mplobj=patch)
375092
def display_graph(g, format='svg', include_asset_exists=False):
    
    try:
        import IPython.display as display
    except ImportError:
        raise NoIPython("IPython is not installed.  Can't display graph.")

    if format == 'svg':
        display_cls = display.SVG
    elif format in ("jpeg", "png"):
        display_cls = partial(display.Image, format=format, embed=True)

    out = BytesIO()
    _render(g, out, format, include_asset_exists=include_asset_exists)
    return display_cls(data=out.getvalue())
700105
def draw(self):
        
        # Set the colors from the supplied values or reasonable defaults
        color_values = resolve_colors(n_colors=4, colors=self.color)

        for idx, metric in enumerate(METRICS):
            # Skip any excluded labels
            if metric not in self.cv_scores_:
                continue

            # Get the color ensuring every metric has a static color
            color = color_values[idx]

            # Make the label pretty
            if metric == "fscore":
                if self.fbeta == 1.0:
                    label = "$f_1$"
                else:
                    label = "$f_{{\beta={:0.1f}}}".format(self.fbeta)
            else:
                label = metric.replace("_", " ")

            # Draw the metric values
            self.ax.plot(
                self.thresholds_, self.cv_scores_[metric],
                color=color, label=label
            )

            # Draw the upper and lower bounds
            lower = self.cv_scores_["{}_lower".format(metric)]
            upper = self.cv_scores_["{}_upper".format(metric)]

            self.ax.fill_between(
                self.thresholds_, upper, lower,
                alpha=0.35, linewidth=0, color=color
            )

            # Annotate the graph with the maximizing value
            if self.argmax.lower() == metric:
                argmax = self.cv_scores_[metric].argmax()
                threshold = self.thresholds_[argmax]
                self.ax.axvline(
                    threshold, ls='--', c='k', lw=1,
                    label="$t_{}={:0.2f}$".format(metric[0], threshold)
                )

        return self.ax
205957
def draw(self, **kwargs):
        
        # Set the axes aspect to be equal
        self.ax.set_aspect("equal")

        # Generate a mask for the upper triangle
        mask = np.zeros_like(self.ranks_, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

        # Draw the heatmap
        # TODO: Move mesh to a property so the colorbar can be finalized
        data = np.ma.masked_where(mask, self.ranks_)
        mesh = self.ax.pcolormesh(data, cmap=self.colormap, vmin=-1, vmax=1)

        # Set the Axis limits
        self.ax.set(
            xlim=(0, data.shape[1]), ylim=(0, data.shape[0])
        )

        # Add the colorbar
        cb = self.ax.figure.colorbar(mesh, None, self.ax)
        cb.outline.set_linewidth(0)

        # Reverse the rows to get the lower left triangle
        self.ax.invert_yaxis()

        # Add ticks and tick labels
        self.ax.set_xticks(np.arange(len(self.ranks_)) + 0.5)
        self.ax.set_yticks(np.arange(len(self.ranks_)) + 0.5)
        if self.show_feature_names_:
            self.ax.set_xticklabels(self.features_, rotation=90)
            self.ax.set_yticklabels(self.features_)
        else:
            self.ax.set_xticklabels([])
            self.ax.set_yticklabels([])
558826
def _make_graph(bsname, version=None, data_dir=None):
    '''
    
    '''

    if not graphviz_avail:
        raise RuntimeError("graphviz package is not installed")

    data_dir = api.fix_data_dir(data_dir)

    md = api._get_basis_metadata(bsname, data_dir)

    if version is None:
        version = md['latest_version']
    else:
        version = str(version)

    if not version in md['versions']:
        raise RuntimeError("Version {} of {} doesn't exist".format(version, bsname))

    gr = graphviz.Digraph(comment='Basis Set Graph: ' + bsname)

    # Read the table file
    table_path = os.path.join(data_dir, md['versions'][version]['file_relpath'])
    table_data = fileio.read_json_basis(table_path)

    table_edges = {}
    for el, entry in table_data['elements'].items():
        if entry not in table_edges:
            table_edges[entry] = []
        table_edges[entry].append(el)

    for k, v in table_edges.items():
        gr.edge(bsname, k, label=compact_elements(v))

    # Element file
    for elfile in table_edges.keys():
        element_path = os.path.join(data_dir, elfile)
        element_data = fileio.read_json_basis(element_path)

        element_edges = {}

        for el, components in element_data['elements'].items():
            components = components['components']
            components_str = '\n'.join(components)

            # skip if this element for the table basis doesn't come from this file
            if el not in table_data['elements']:
                continue
            if table_data['elements'][el] != elfile:
                continue

            if components_str not in element_edges:
                element_edges[components_str] = []
            element_edges[components_str].append(el)

        for k, v in element_edges.items():
            if len(v):
                gr.edge(elfile, k, label=compact_elements(v))

    return gr