示例#1
0
def plot(drama, caption=True):

    plot = ig.Plot(outputfolder + drama.get("title") + ".png",
                   bbox=(600, 600),
                   background="white")

    try:
        graph = ig.VertexClustering(drama.get("graph")).giant()
        visual_style = {}
        visual_style["layout"] = graph.layout_fruchterman_reingold()
        visual_style["vertex_color"] = "#0000ff"
        visual_style["vertex_shape"] = "rectangle"
        visual_style["vertex_size"] = 8
        visual_style["vertex_label"] = graph.vs["name"]
        visual_style["vertex_label_size"] = 15
        visual_style["vertex_label_dist"] = 1.5
        visual_style["edge_color"] = "#6495ed"
        visual_style["edge_width"] = graph.es["weight"]
        visual_style["bbox"] = (600, 600)
        visual_style["margin"] = 50
        plot.add(graph, **visual_style)
    except:
        pass

    if caption:
        # Make the plot draw itself on the Cairo surface.
        plot.redraw()

        # Grab the surface, construct a drawing context and a TextDrawer.
        ctx = cairo.Context(plot.surface)
        ctx.set_font_size(15)
        drawer = TextDrawer(ctx, drama.get("title"), halign=TextDrawer.CENTER)
        drawer.draw_at(0, 597, width=600)

    plot.save()
示例#2
0
def _draw_title(title, surface, width, height):
    ctx = cairo.Context(surface)
    ctx.set_font_size(TITLE_FONT_SIZE)
    drawer = TextDrawer(ctx,
                        title,
                        halign=TextDrawer.CENTER,
                        valign=TextDrawer.TOP)
    drawer.draw_at(0, PLOT_MARGIN[2] / 3, width=width)
示例#3
0
def plot(graph, source_path, index, result_path=None, compute_closeness=True, print_label_size_min=None,
         add_legend=True, size_factor=None, bbox_size=None):
    graph_object = deepcopy(graph)
    l = read_cache(source_path)
    if not l:
        l = graph_object.layout(PLOT_LAYOUT)
        save_cache(source_path, l)
    logging.info('complete layout')

    if not result_path:
        result_path = source_path

    png_opt = dict(bbox=(1500, 1500), vertex_size=7, edge_arrow_size=0.2, edge_arrow_width=0.9, edge_width=0.3,
                   vertex_frame_width=0.4) if index not in PLOT_OPTIONS_PNG else PLOT_OPTIONS_PNG[index]

    if bbox_size:
        png_opt['bbox'] = (bbox_size, bbox_size)

    if print_label_size_min is None:
        graph_object.vs['label'] = ['']
    else:
        for i in graph_object.vs:
            try:
                if i['size'] < print_label_size_min:
                    i['label'] = ''
            except IndexError:
                pass

    if size_factor:
        m = max(graph_object.vs['size'])
        for i in graph_object.vs:
            try:
                i['size'] = i['size'] / m * size_factor
            except IndexError:
                pass

    p = igraph.plot(graph_object, plot_name(result_path, 'png'), layout=l, **png_opt)
    logging.info('plot graph')
    if add_legend:
        legend = '%s: %d x %d\nclustering coef. %.4f\n' % (index, graph_object.vcount(), graph_object.ecount(),
                                                           graph_object.transitivity_undirected(mode="zero"))
        if compute_closeness:
            legend += 'closeness %.4f' % (sum(graph_object.closeness()) / graph_object.vcount())
        logging.info('compute legend %s' % legend)
        p.redraw()
        ctx = cairocffi.Context(p.surface)
        ctx.set_font_size(40)
        # todo Use ctx.scale() for big image
        drawer = TextDrawer(ctx, legend, halign=TextDrawer.LEFT)
        drawer.draw_at(150, 50, width=500)
    p.save()
    logging.info('save png')
示例#4
0
def plot_polar_graph(graph,
                     legend,
                     fill,
                     vertex_coords,
                     vertex_frame_color,
                     main_title,
                     subtitle,
                     filename=None):

    bbox = igraph.BoundingBox(800, 800)
    plot = igraph.Plot(filename, bbox=bbox, background="white")
    bbox = bbox.contract(50)
    plot.add(graph,
             bbox=(50, 110, 750, 690),
             layout=vertex_coords,
             edge_arrow_size=1.5,
             vertex_shape='circle',
             vertex_frame_color=vertex_frame_color,
             vertex_frame_width=1,
             vertex_size=30)
    plot.redraw()

    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(36)
    drawer = TextDrawer(ctx, main_title, halign=TextDrawer.CENTER)
    drawer.draw_at(0, 40, width=800)
    ctx.set_font_size(20)
    drawer = TextDrawer(ctx, subtitle, halign=TextDrawer.CENTER)
    drawer.draw_at(0, 750, width=800)

    plot.save()
示例#5
0
def make_graph( node_id_map, nodes, edges, edges_predicate, output_fn, tag ):
    g = Graph()
    g.add_vertices( len(nodes))
    graph_edges = list( [node_id_map[e.image_A_id], node_id_map[e.image_B_id]] \
                         for e in edges if edges_predicate(e))
    g.add_edges( graph_edges)
    layout = g.layout_circle()
    # adding text to plot courtesy http://stackoverflow.com/questions/18250684/add-title-and-legend-to-igraph-plots
    plot = Plot(output_fn, bbox=[2000,2000])
    plot.add( g, layout=layout, bbox=[50,50,1950,1950])
    ctx = cairo.Context( plot.surface )
    ctx.set_font_size(36)
    drawer = TextDrawer( ctx, "Label: '%s'\n%s\n%d nodes, %d edges" % \
                         (LABEL, tag, len(nodes), len(graph_edges)), halign=TextDrawer.RIGHT)
    drawer.draw_at(10,1900,width=1900)
    plot.save()
    sys.stderr.write("Info: wrote %s\n" % output_fn)
示例#6
0
def graph_plot(graph, visual_style, texts=None):
    """
        @param graph:
        
        @param visual_style:
        
        @param texts: a dictionary storing the text to be printed with text[key]: [x,y, fontsize]
        e.g texts["M1"] = [0, 180, 30]
        
        @return igplot: an igraph.drawing.Plot object
    """

    # an igraph.drawing.Plot object
    igplot = ig.plot(graph, **visual_style)

    # plot text
    if texts is not None:

        igplot.redraw()

        # Context object
        ctx = cairo.Context(igplot.surface)

        # draw each text in ig.plot
        for text in texts:
            val = texts[text]

            # fontsize
            try:
                fontsize = val[2]

            except IndexError:
                fontsize = 20

            # set the font size
            ctx.set_font_size(fontsize)

            # TextDrawer Object
            drawer = TextDrawer(ctx, text, halign=TextDrawer.CENTER)

            # draw the text at the coordinates coord
            drawer.draw_at(x=val[0], y=val[1], width=300)

    return igplot
示例#7
0
 def plot_network(self, title='Network', membership=None, 
                  outfile=None, width=900, height=600):
     if self.edgelist is None:
         self.edgelist = self.get_edgelist()
     if self.g is None:
         self.g = ig.Graph(self.edgelist)
     if membership is None:
         membership = self.get_membership()
         pal_size = max(1, len(self.cluster))   
     else:
         temp = set()
         for item in membership:
             temp.add(item)
         pal_size = max(1, len(temp))
     pal = ig.ClusterColoringPalette(pal_size)
     visual_style = {}
     visual_style['vertex_color'] = [pal.get(id) \
                                     for id in membership]
     if self.size <= 100:
         visual_style['vertex_size'] = 20
         visual_style['vertex_label'] = [str(id+1) \
                                         for id in xrange(self.size)]
     else:
         visual_style['vertex_size'] = 8
     if not self.layout:
         if self.size <= 200:
             self.layout = self.g.layout('kk')
         else:
             self.layout = self.g.layout('lgl') 
     visual_style['margin'] = (20,50,20,20)
     visual_style['layout'] = self.layout
     visual_style['bbox'] = (width, height)
     figure = ig.plot(self.g, **visual_style)
     figure.redraw()
     ctx = cairo.Context(figure.surface)
     ctx.set_font_size(20)
     drawer = TextDrawer(ctx, title, halign=TextDrawer.CENTER)
     drawer.draw_at(3,30, width=width)
     if outfile:
         figure.save(outfile)
     figure.show()
示例#8
0
def plot_four(g1, g2, g3, g4, title):
    """ Plots four graphs on a single plot.
    """
    # Construct plot
    plot = igraph.Plot(title, bbox=(1200, 940), background="white")
    plot.add(g1, bbox=(20, 60, 580, 470))
    plot.add(g2, bbox=(620, 60, 1180, 470))
    plot.add(g3, bbox=(20, 510, 580, 920))
    plot.add(g4, bbox=(620, 510, 1180, 920))

    plot.redraw()
    # Add title
    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(24)
    drawer = TextDrawer(ctx,
                        'crime count: {}, zip code count: {}'.format(
                            sum([int(i) for i in g1.vs['description']]),
                            g1.vcount()),
                        halign=TextDrawer.CENTER)
    drawer.draw_at(0, 40, width=1200)
    plot.save()
示例#9
0
def plot_polar_graph(
    graph,
    legend,
    fill,
    vertex_coords,
    vertex_frame_color,
    main_title,
    subtitle,
    filename=None):

    bbox = igraph.BoundingBox(800,800)
    plot = igraph.Plot(filename, bbox=bbox, background="white")
    bbox = bbox.contract(50)
    plot.add(graph,bbox=(50,110,750,690),
        layout=vertex_coords,
        edge_arrow_size=1.5,
        vertex_shape='circle',
        vertex_frame_color=vertex_frame_color,
        vertex_frame_width=1,
        vertex_size=30)
    plot.redraw()

    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(36)
    drawer = TextDrawer(ctx, main_title, halign=TextDrawer.CENTER)
    drawer.draw_at(0, 40, width=800)
    ctx.set_font_size(20)
    drawer = TextDrawer(ctx, subtitle, halign=TextDrawer.CENTER)
    drawer.draw_at(0, 750, width=800)

    plot.save()
示例#10
0
  def DrawGraph(self, fn, title=None): 
    # Draw graph and save to file.
    plot = igraph.Plot(fn, bbox = (900, 780), background="white")
    if self.style['layout'] == None:
      self.style['layout'] = self.g.layout("kk")

    low = min( map(lambda(agent) : agent.initialOpinion, self.g.vs['agency']) )
    high = max( map(lambda(agent) : agent.initialOpinion, self.g.vs['agency']) )
    for (u, agent) in self.IterAgents():
      u['color'] = ScaleColor(UNSHIFT(agent.opinion) / UNSHIFT(high))
      u['label'] = agent.GetLabel()
      u['label_dist'] = 2
      u['label_size'] = 10

    plot.add(self.g, **self.style)
    plot.redraw()
    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(22)
    if title:
      drawer = TextDrawer(ctx, title, halign=TextDrawer.CENTER)
      drawer.draw_at(0, 40, width=900)
   
    ctx.set_font_size(18)
    drawer = TextDrawer(ctx, 'Round No. %d' % self.round_no, halign=TextDrawer.RIGHT)
    drawer.draw_at(860, 770, width=9)
    
    plot.save()
示例#11
0
from igraph import Graph, Plot
from igraph.drawing.text import TextDrawer
import cairo

# Construct the plot
plot = Plot("plot.png", bbox=(600, 650), background="white")

# Create the graph and add it to the plot
g = Graph.GRG(100, 0.2)
plot.add(g, bbox=(20, 70, 580, 630))

# Make the plot draw itself on the Cairo surface
plot.redraw()

# Grab the surface, construct a drawing context and a TextDrawer
ctx = cairo.Context(plot.surface)
ctx.set_font_size(36)
drawer = TextDrawer(ctx, "Test title", halign=TextDrawer.CENTER)
drawer.draw_at(0, 40, width=600)

# Save the plot
plot.save()
示例#12
0
def plotgraph(filename, characters, title, community=True):
    m = len(characters)
    g = Graph()
    g.add_vertices(m)
    for i in range(m):
        if type(characters[i]) is list:
            g.vs[i]['label'] = characters[i][0]
        else:
            g.vs[i]['label'] = characters[i]
    for i in range(m):
        for j in range(i, m):
            g.add_edge(i, j)
            g.es[g.get_eid(i, j)]['weight'] = 0

    with open(filename + '.pdf', 'rb') as f:
        pdf = pdftotext.PDF(f)
        for pg in pdf:
            tmp = [0] * m
            for i in range(m):
                if type(characters[i]) is list:
                    for charname in characters[i]:
                        if pg.find(charname) != -1:
                            tmp[i] = 1
                else:
                    if pg.find(characters[i]) != -1:
                        tmp[i] = 1
            for i in range(m):
                if not tmp[i]:
                    continue
                for j in range(m):
                    if tmp[j] and i != j:
                        g.es[g.get_eid(i, j)]['weight'] += 1

    maxweight = 0
    for e in g.es:
        if maxweight < e['weight']:
            maxweight = e['weight']

    g1 = g.copy()
    edges_to_delete = []
    for e in g1.es:
        if e['weight'] < maxweight / 30:
            edges_to_delete.append(e)
    g1.delete_edges(edges_to_delete)
    if community:
        cl = g1.community_fastgreedy(weights=g1.es['weight'])
        membership = cl.as_clustering().membership
        edges_to_delete = []
        for e in g1.es():
            if membership[e.tuple[0]] != membership[e.tuple[1]]:
                edges_to_delete.append(e)
        g1.delete_edges(edges_to_delete)

    edges_to_delete = []
    for e in g.es:
        if e['weight'] < maxweight / 50:
            edges_to_delete.append(e)
    g.delete_edges(edges_to_delete)
    vertices_to_delete = []
    for v in g.vs:
        if v.degree() < 1:
            vertices_to_delete.append(v)
    g.delete_vertices(vertices_to_delete)
    g1.delete_vertices(vertices_to_delete)

    coords = g1.layout_kamada_kawai()

    for e in g.es:
        e['width'] = e['weight'] * 4 / maxweight
    visual_style = {
        'vertex_size': 5,
        'vertex_label_size': 18,
        'vertex_label_dist': 3,
        'bbox': (1000, 1000),
        'margin': 120,
        'edge_curved': True
    }

    plot = Plot(target=filename + '.png',
                bbox=(1000, 1000),
                background="white")
    plot.add(g, layout=coords, **visual_style)
    plot.redraw()
    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(24)
    drawer = TextDrawer(ctx, title, halign=TextDrawer.CENTER)
    drawer.draw_at(0, 40, width=1000)
    plot.save()
示例#13
0
def buildGraphAcctBal(networkGraph2):
    fileName = "NetworkWikiAcctBalanceWD2018.png"
    color_dict = {"G20": "blue", "NotG20": "yellow", "No Data": "gray"}
    color_dict_edge = {"G20": "#5bbbfb", "NotG20": "#95afc0"}

    visual_style = {}
    visual_style["vertex_label_size"] = 15
    visual_style["vertex_label_color"] = "#130f40"
    visual_style["edge_color"] = "#95afc0"
    visual_style["vertex_size"] = 0

    total = 0
    tc = 0
    counter = 0

    for acctBal in networkGraph2.vs["account-balance"]:
        if acctBal == 0:
            networkGraph2.vs[counter]["status"] = "No Data"
            counter += 1

        else:
            counter += 1
            tc += 1
            total += acctBal

    total = total / tc


    visual_style["vertex_size"] = [10 + (balance - total) for balance in \
                        networkGraph2.vs["account-balance"]]
    visual_style["vertex_color"] = [color_dict[status] for status in \
                        networkGraph2.vs["status"]]
    ce = 0
    for edge in networkGraph2.es:
        v1 = "NotG20"
        v2 = "NotG20"

        if networkGraph2.vs[edge.target]["name"] in G20_NAMES:
            v1 = "G20"
        if networkGraph2.vs[edge.source]["name"] in G20_NAMES:
            v2 = "G20"
        if v1 == "G20" and v2 == "G20":
            networkGraph2.es[ce]["connection_type"] = "G20"
        else:
            networkGraph2.es[ce]["connection_type"] = "NotG20"
        ce += 1

    visual_style["edge_color"] = [color_dict_edge[conntype] for conntype in \
                        networkGraph2.es["connection_type"]]

    networkGraph2.vs["label"] = networkGraph2.vs["name"]
    layout = networkGraph2.layout("rt_circular")

    plot2 = Plot(fileName, bbox=(1100, 1100), background="#dff9fb")
    plot2.add(networkGraph2, bbox= (55, 55, 900, 900), layout = layout, \
                                    **visual_style)

    plot2.redraw()

    ctx = cairo.Context(plot2.surface)
    ctx.set_font_size(20)
    drawer = TextDrawer(ctx, "Wikipedia G20 Network Analysis viz. AcctBalance",\
                            halign=TextDrawer.CENTER)
    drawer.draw_at(0, 40, width=1000)

    plot2.save()
示例#14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('file')
    parser.add_argument('--key-label', default='AstChild', type=str)
    parser.add_argument('--layout',
                        default='rt',
                        help='for big graphs, try rt_circular')
    parser.add_argument('--node-color', default='viridis')
    parser.add_argument('--edge-color', default='viridis')
    args = parser.parse_args()

    with open(args.file) as f:
        json_f = json.load(f)
        nodes = json_f['nodes']
        edges = json_f['edges']

    G = Graph()
    dG = Graph(directed=True)
    for n in nodes:
        G.add_vertex(str(n['id']))
        dG.add_vertex(str(n['id']))

    if all('token' in n for n in nodes):
        dG.vs["label"] = [n['token'] for n in nodes]

    dG.vs['color'] = colorize([n['ast_type'] for n in nodes], args.node_color)
    for c in dG.vs['color']:
        c[-1] = 0.4

    def proc_edges(es):
        return [(str(e['src']), str(e['dst'])) for e in es]

    def edge_of_label(lab):
        return list(e for e in edges if e['edge_type'] == lab)

    key_label = args.key_label
    rest_labels = list(set(e['edge_type'] for e in edges) - {key_label})

    cidxmap = {key_label: 0}
    cs = [key_label] * len(edge_of_label(key_label))
    for rl in rest_labels:
        cidxmap[rl] = len(cs)
        cs += [rl] * len(edge_of_label(rl))

    dG.add_edges(proc_edges(edge_of_label(key_label)))
    for rl in rest_labels:
        dG.add_edges(proc_edges(edge_of_label(rl)))

    print('{:.2f} {:.2f} {}'.format(
        np.mean(dG.degree()),
        dG.average_path_length(),
        dG.diameter(),
    ))
    return

    G.add_edges(proc_edges(edge_of_label(key_label)))
    lay = G.layout(args.layout)

    dG.es['color'] = colorize(cs, args.edge_color)

    plot = Plot("plot.png", bbox=(800, 670), background="white")

    plot.add(dG, layout=lay, vertex_size=40, bbox=(40, 70, 580, 630))
    plot.redraw()

    # Grab the surface, construct a drawing context and a TextDrawer
    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(20)

    drawer = TextDrawer(ctx, "Legend", halign=TextDrawer.CENTER)
    drawer.draw_at(680, 40, width=40)

    ctx.rectangle(620, 20, 160, 125)
    ctx.rectangle(620, 48, 160, 1)
    ctx.stroke()
    ctx.set_source_rgb(0., 0., 0.)

    ctx.set_font_size(18)
    y = 40 + 30
    for lab in [key_label] + rest_labels:
        ctx.set_source_rgb(*dG.es['color'][cidxmap[lab]][:3])
        ctx.rectangle(640, y - 8, 20, 1)
        ctx.stroke()
        ctx.set_source_rgb(0., 0., 0.)
        drawer = TextDrawer(ctx, str(lab), halign=TextDrawer.CENTER)
        drawer.draw_at(700, y, width=40)
        y += 15

    # Save the plot
    plot.save()
示例#15
0
        # degree for vertex_size
        strength = g.strength(weights='weight')
        visual_style['vertex_size'] = np.array(strength) / max(
            strength) * max_size

        # plot graph grouped by communities
        plot = ig.Plot('./figures/time/graph-%s.png' % str(i),
                       bbox=(1000, 1000),
                       background="white")
        plot.add(g, **visual_style)
        # Make the plot draw itself on the Cairo surface
        plot.redraw()
        # Grab the surface, construct a drawing context and a TextDrawer
        ctx = cairo.Context(plot.surface)
        ctx.set_font_size(28)
        drawer = TextDrawer(ctx, time_range, halign=TextDrawer.CENTER)
        drawer.draw_at(0, 80, width=1000)

        # Save the plot
        plot.save()
        print('graph saved')

        # current date + 1 month
        current = current + relativedelta(months=1)
        # increase counter
        i += 1

########################################################################
# TIME ANALYSIS / DYNAMICS

# detect changes
示例#16
0
    elif v.degree() > 7:
        v['color'] = 'green'
        v['size'] = 30
    elif v.degree() > 6:
        v['color'] = 'pink'
        v['size'] = 20

# Construimos el plot
plot = Plot("smallworld.png", bbox=(600, 400), background="white")
plot.add(g1, bbox=(20, 80, 500, 300))
# Añadimos el grafo al plot
plot.redraw()
# Preparamos el canvas donde escribiremos el grafo
ctx = cairo.Context(plot.surface)
ctx.set_font_size(14)
## Dibujamos la leyenda
drawer = TextDrawer(ctx, "Cyan : Degree(v)>9", halign=TextDrawer.RIGHT)
drawer.draw_at(0, 20, width=580)
drawer = TextDrawer(ctx, "Amarillo : Degree(v)>8", halign=TextDrawer.RIGHT)
drawer.draw_at(0, 40, width=580)
drawer = TextDrawer(ctx, "Verde : Degree(v)>7", halign=TextDrawer.RIGHT)
drawer.draw_at(0, 60, width=580)
drawer = TextDrawer(ctx, "Rosa : Degree(v)>6", halign=TextDrawer.RIGHT)
drawer.draw_at(0, 80, width=580)
drawer = TextDrawer(ctx, "Rojo : Degree(v)<=5", halign=TextDrawer.RIGHT)
drawer.draw_at(0, 100, width=580)

# Save the plot
plot.save()
plot.show()
示例#17
0
lay_kk = gg.layout('kk')
pp_kk = ig.plot(gg, layout=lay_kk)

lay_lgl = gg.layout('lgl')
pp_lgl = ig.plot(gg, layout=lay_lgl)
pp_lgl.show()

g.vs['size'] = 20
g.vs['color'] = [color_list[id] for id in cd.membership]
lay_kk = g.layout('kk')

pp_kk = ig.plot(g, target='haha.pdf',margin=(20,50,20,20), layout=lay_kk)
pp_kk.redraw()
ctx = cairo.Context(pp_kk.surface)
ctx.set_font_size(20)
drawer = TextDrawer(ctx, "Test title", halign=TextDrawer.CENTER)
drawer.draw_at(3, 30, width=600)
pp_kk.show()

pp_kk.show()
pp_lgl.show()

#generate graph from stochastic block model
gg = ig.Graph.SBM(n=120, pref_matrix=list(prob1), 
                  block_sizes=list(size1))

#gg = ig.Graph.Erdos_Renyi(100, 0.1)

cc = gg.community_leading_eigenvector()

adjlist = gg.get_adjlist()
示例#18
0
    def plot(self, t):
        visual_style = {}
        visual_style["vertex_size"] = 20
        visual_style["layout"] = self.g.layout("grid")
        visual_style["vertex_label"] = range(self.g.vcount())

        ## Presence Graph
        self.g.vs["color"] = "yellow"
        self.g.vs[self.target.position]["color"] = "red"
        # for idx in self.searchers.positions:
        #   self.g.vs[idx]["color"] = "green"
        for idx in range(self.N):
            if self.capture[idx, t].X[0]:
                self.g.vs[idx]["color"] = "green"
                if idx == self.target.position:
                    self.g.vs[idx]["color"] = "#fc03db"

        ## Belief Graph
        self.belief_g.vs["color"] = '#4287f5'

        capture_belief = self.beliefs[0, t].X[0]
        capture_belief = round(capture_belief, 2)  # Round to 2 decimals
        capture_belief = abs(capture_belief)  # To get rid of "-0.00"
        belief_array = np.array(
            [round(b.X[0], 2) for b in self.beliefs[1:, t]])
        max_belief = np.max(belief_array)
        for idx in range(self.N):
            if belief_array[idx] > 0:
                alpha = int(255 * belief_array[idx] / max_belief)
                # Alpha value defines opacity of color
                # We use it to denote how confident we think the
                # target is situated in that vertex
                self.belief_g.vs[idx]["color"] = f'#ff0000{alpha:0>2x}'

        # Construct the plot
        WIDTH = 700
        GRAPH_WIDTH = 560
        L = 70
        H = 100
        plot = ig.Plot(os.path.join(sys.path[0], f'../results/path_t={t}.png'),
                       bbox=(2 * WIDTH, WIDTH),
                       background="white")
        # Add the graphs to the plot
        plot.add(self.g,
                 bbox=(L, H, L + GRAPH_WIDTH, H + GRAPH_WIDTH),
                 **visual_style)
        plot.add(self.belief_g,
                 bbox=(WIDTH + L, H, WIDTH + L + GRAPH_WIDTH, H + GRAPH_WIDTH),
                 **visual_style)
        # Make the plot draw itself on the Cairo surface
        plot.redraw()
        # Grab the surface, construct a drawing context and a TextDrawer
        ctx = cairo.Context(plot.surface)
        ctx.set_font_size(24)
        title = f"[Positions and Beliefs at t={t}]\n"
        title += f"Max occupancy belief: {max_belief}, "
        title += f"Capture belief: {capture_belief}"
        drawer = TextDrawer(ctx, title, halign=TextDrawer.CENTER)
        drawer.draw_at(0, 40, width=2 * WIDTH)
        # Save the plot
        plot.save()
示例#19
0
def render_igraph(mol_net,
                  save_name=None,
                  layout='auto',
                  title=None,
                  positions=None,
                  cluster=False,
                  node_size=50,
                  bbox=None,
                  margin=None,
                  inline=False):
    """

    Parameters
    ----------

    mol_net : networkx.DiGraph
        networkx graph
    save_name : str
        Save name
    layout : str
    title : str, optional
    positions : list, optional
    bbox : list
    cluster : bool
    margin : list
    node_size : int
    Returns
    -------

    """
    try:
        import cairo
    except ImportError:
        print("Please install pycairo to use igraph plotting")
        return

    try:
        import igraph
        from igraph.drawing.text import TextDrawer
        from igraph.drawing.colors import color_name_to_rgba
    except ImportError:
        print("No igraph, cannot use plotting function")
        return
    g = nx_to_igraph(mol_net)
    if not isinstance(g, igraph.Graph):
        print("Error converting to Igraph")
        return
    if bbox is None:
        bbox = [2400, 2400]
    if margin is None:
        margin = [50, 50, 50, 50]

    _valid_layouts = {
        "kk", "drl", "lgl", "tree", "graphopt", "mds", "sugiyama", "auto"
    }
    assert layout in _valid_layouts, \
        'layout {} not in {}'.format(layout, _valid_layouts)

    mark_groups = None
    membership = None

    if cluster and 'termName' in g.vs.attributes():
        cl = igraph.VertexClustering(g).FromAttribute(g, attribute='termName')
        membership = cl.membership
        if membership is not None:
            gcopy = g.copy()
            # edges = []
            # for edge in g.es():
            #     if membership[edge.tuple[0]] != membership[edge.tuple[1]]:
            #         edges.append(edge)
            # gcopy.delete_edges(edges)
            if positions is None:
                positions = gcopy.layout(layout)
            n_clusters = len(set(membership))
            rgb_colors = sns.color_palette("tab20", n_clusters)
            colors = rgb_colors.as_hex()
            mark_groups = dict()
            for n, color in enumerate(colors):
                mem = tuple(i for i, j in enumerate(membership) if j == n)
                mark_groups[mem] = color

    if positions is None:
        positions = g.layout(layout)

    visual_style = dict()
    visual_style["vertex_label_dist"] = 0
    visual_style["vertex_shape"] = "circle"
    visual_style["vertex_size"] = node_size
    visual_style["layout"] = positions
    visual_style["margin"] = margin
    # visual_style["edge_curved"] = True

    if 'color' in g.es.attributes():
        visual_style["edge_color"] = g.es["color"]

    if save_name is not None:
        if not save_name.endswith('.png'):
            save_name += '.png'

    if cluster:
        # add some white space to add labels
        bbox_plus_margin = [bbox[0] + bbox[0] * .45, bbox[1] + bbox[0] * .1]
        margin[2] += bbox[0] * .25
        margin[0] += bbox[0] * .05
    else:
        bbox_plus_margin = bbox

    # create entire surface
    plot = igraph.Plot(save_name, bbox=bbox_plus_margin, background='white')

    # add plot to surface
    plot.add(g, mark_groups=mark_groups, bbox=bbox, **visual_style)

    # have to redraw to add the plot
    plot.redraw()

    if membership is not None:
        # Grab the surface, construct a drawing context and a TextDrawer
        ctx = cairo.Context(plot.surface)
        ctx.set_font_size(36)
        if title is not None:
            drawer = TextDrawer(ctx, title, halign=TextDrawer.CENTER)
            drawer.draw_at(0, 40, width=600)

        labels = dict()
        for vertex in g.vs():
            name = vertex['termName'].replace(',', '\n')
            if name in labels:
                continue
            labels[name] = rgb_colors[membership[vertex.index]]
        spacing = bbox[1] / len(labels)
        ctx.set_font_size(24)
        for n, (label, rgb_c) in enumerate(labels.items()):
            text_drawer = TextDrawer(ctx, text=label, halign=TextDrawer.LEFT)
            x_coord = bbox[0] + 25
            y_coord = 100 + (n * spacing)
            text_drawer.draw_at(x=x_coord, y=y_coord, width=300, wrap=True)
            ctx.set_source_rgba(*rgb_c)
            ctx.arc(x_coord - 1.5 * node_size, y_coord, node_size, 0, 6.28)
            ctx.fill()
            ctx.set_source_rgba(0, 0, 0, 1)
    # Save the plot
    if save_name is not None:
        plot.save()
    if inline:
        return plot

    return plot, positions
示例#20
0
def plot_coefficient(self, i, j):
    import cairo
    from igraph.drawing.text import TextDrawer
    random.seed(1)
    g = self.graphList[i].graph
    if(g != None and len(g.vs["name"]) < 1000):
        #layout = g.layout("kamada_kawai")
        layout = g.layout("fr")

        g.es["curved"] = False
        visual_style = {}
        visual_style["vertex_size"] = 20
        #visual_style["vertex_color"] = [color_dict[gender] for gender in g.vs["gender"]]
        visual_style["vertex_label"] = g.vs["name"]
        l = self.graphList[i].centrality[j]
        m = max(l)
        l1 = [(float(l[i]) / float(m)) * 100 for i in range(len(l))]

        col = []
        pal = RainbowPalette(n=120)
        for n, val in enumerate(l1):
            col.append(pseudocolor(val,0,100))

        visual_style["vertex_color"] = col

        visual_style["edge_width"] = [float(weight) for weight in g.es["weight"]]
        visual_style["edge_color"] = ["red" if (w < 0) else "black" for w in g.es["weight"]]
        visual_style["edge_color"] = ["red" if (w < 0) else "black" for w in g.oldes]

        visual_style["layout"] = layout
        #visual_style["bbox"] = (800, 800)
        visual_style["margin"] = 20
        visual_style["edge-curved"] = False


        plot = Plot("plot.png", bbox=(720, 760), background="white")

        # # Create the graph and add it to the plot
        plot.add(g, bbox=(20, 80, 580, 630), **visual_style)

        # save_img = PhotoImage(file="save.gif")
        #plot.add(save_img, bbox=(20, 70, 580, 630))

        # Make the plot draw itself on the Cairo surface
        plot.redraw()

        # Grab the surface, construct a drawing context and a TextDrawer
        ctx = cairo.Context(plot.surface)
        ctx.set_font_size(36)
        drawer = TextDrawer(ctx, columnNames[j+1], halign=TextDrawer.CENTER)
        drawer.draw_at(0, 40, width=600)

        image_surface = cairo.ImageSurface.create_from_png("rainbow.png")
        ctx.set_source_surface(image_surface, 55, 680)
        ctx.paint()
        
        #ctx.plot(image_surface, target=None, bbox=(0, 0, 600, 600))
        #plot.add(image_surface, bbox=(20, 20, 580, 580))

        print type(plot)

        return plot
示例#21
0
def draw_igraph(mol_net, save_name=None, layout='auto', title=None,
                positions=None, cluster=False, node_size=50,
                bbox=None, margin=None, inline=False, node_font_size=24,
                font_size=36):
    """

    Parameters
    ----------

    mol_net : networkx.DiGraph
        networkx graph
    save_name : str
        Save name
    layout : str
        Options = "kk", "fr", "drl", "lgl", "tree", "graphopt", "mds", "sugiyama",
        "auto", "grid_fr"
    title : str, optional
    positions : list, optional
    bbox : list
    cluster : bool
        Add a shape around species that are tagged the same.
         g.node[0][term_name]='dna'
         g.node[0][term_name]='dna'
         This will be grouped together.
    margin : list
        Margin of white space for boxes. This should be considered for the
         labels of the nodes
    node_size : int
    node_font_size: int
        Size of node labels
    font_size : int
        Title and group name (if clustering) font size
    inline : bool
        Return plot as svg view ipython

    Returns
    -------

    """
    try:
        import cairo
    except ImportError:
        ImportError("Please install pycairo to use igraph plotting")

    try:
        import igraph
        from igraph.drawing.text import TextDrawer
        from igraph.drawing.colors import color_name_to_rgba
    except ImportError:
        raise ImportError("No igraph, cannot use plotting function")

    if isinstance(mol_net, igraph.Graph):
        g = mol_net
    else:
        g = nx_to_igraph(mol_net)
        if not isinstance(g, igraph.Graph):
            print("Error converting to Igraph")
            return
    if inline:
        if bbox is None:
            bbox = [500, 500]
        if margin is None:
            margin = [50, 50, 50, 50]

    if bbox is None:
        bbox = [2400, 2400]
    if margin is None:
        margin = [50, 50, 50, 50]

    _valid_layouts = {
        "kk", "fr", "drl", "lgl", "tree", "graphopt", "mds", "sugiyama",
        "auto", "grid_fr",
    }
    if layout not in _valid_layouts:
        raise Exception('layout {} not in {}'.format(layout, _valid_layouts))

    mark_groups = None
    membership = None

    if cluster and 'termName' in g.vs.attributes():
        cl = igraph.VertexClustering(g).FromAttribute(g, attribute='termName')
        membership = cl.membership
        if membership is not None:
            gcopy = g.copy()
            # edges = []
            # for edge in g.es():
            #     if membership[edge.tuple[0]] != membership[edge.tuple[1]]:
            #         edges.append(edge)
            # gcopy.delete_edges(edges)
            if positions is None:
                positions = gcopy.layout(layout)
            n_clusters = len(set(membership))
            rgb_colors = sns.color_palette("tab20", n_clusters)
            colors = rgb_colors.as_hex()
            mark_groups = dict()
            for n, color in enumerate(colors):
                mem = tuple(i for i, j in enumerate(membership) if j == n)
                mark_groups[mem] = color

    if positions is None:
        positions = g.layout(layout)

    visual_style = dict()
    visual_style["vertex_label_dist"] = 0
    visual_style["vertex_shape"] = "circle"
    visual_style["vertex_size"] = node_size
    visual_style["vertex_label_size"] = node_font_size
    visual_style["layout"] = positions
    visual_style["margin"] = margin
    # visual_style["edge_curved"] = True

    if 'color' in g.es.attributes():
        visual_style["edge_color"] = g.es["color"]

    if save_name is not None:
        if not save_name.endswith('.png'):
            save_name += '.png'

    if cluster:
        # add some white space to add labels
        bbox_plus_margin = [bbox[0] + bbox[0] * .45, bbox[1] + bbox[0] * .1]
        margin[2] += bbox[0] * .25
        margin[0] += bbox[0] * .05
    else:
        bbox_plus_margin = bbox

    # create entire surface
    plot = igraph.Plot(save_name,
                       bbox=bbox_plus_margin,
                       background='white')

    # add plot to surface
    plot.add(g, mark_groups=mark_groups, bbox=bbox, **visual_style)

    # have to redraw to add the plot
    plot.redraw()

    # Grab the surface, construct a drawing context and a TextDrawer
    ctx = cairo.Context(plot.surface)
    ctx.set_font_size(font_size)

    if title is not None:
        drawer = TextDrawer(ctx, title, halign=TextDrawer.CENTER)
        drawer.draw_at(0, 40, width=600)

    if membership is not None:
        labels = dict()
        for vertex in g.vs():
            name = vertex['termName'].replace(',', '\n')
            if name in labels:
                continue
            labels[name] = rgb_colors[membership[vertex.index]]
        spacing = bbox[1] / len(labels)
        ctx.set_font_size(24)
        for n, (label, rgb_c) in enumerate(labels.items()):
            text_drawer = TextDrawer(ctx, text=label, halign=TextDrawer.LEFT)
            x_coord = bbox[0] + 25
            y_coord = 100 + (n * spacing)
            text_drawer.draw_at(x=x_coord, y=y_coord, width=300, wrap=True)
            ctx.set_source_rgba(*rgb_c)
            ctx.arc(x_coord - 1.5 * node_size, y_coord, node_size, 0, 6.28)
            ctx.fill()
            ctx.set_source_rgba(0, 0, 0, 1)
    # Save the plot
    if save_name is not None:
        plot.save()
    if inline:
        return plot

    return plot, positions