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()
def Plot(database, width=1000, height=1000, path=None, do_save=True, target=None, vx_mapping=None, **kwargs): """Plot the currrent graph. This **returns** the graph as igraph plot. If you want to use the Plot for drawing it interactively, you can access it's .surface attribute. """ try: import igraph except ImportError: print('-- You need igraph and python-igraph installed for plotting.') return graph = igraph.Graph(directed=False) _build_graph_from_song_list(graph, database) style = _style(graph, vx_mapping or {}, width, height) style.update(kwargs) path = path or '/tmp/.munin_plot.png' bg_color = "rgba(100%, 100%, 100%, 100%)" plot = igraph.Plot(target=target, background=bg_color, bbox=(width, height)) plot.add(graph, **style) plot.redraw() if do_save: plot.save(path) return plot.surface
def draw_graph(self, file_path, least_community=None): """ :param file_path: 社区图保存路径 :param least_community: 当社区的点的个数少于该值 则不画出来;若值为None则画出全部点和社区 :return: """ if least_community is not None: sub_vertex = [] for community in self.MG.divide_result: if community.__len__() >= least_community: sub_vertex += community sub_vertex.sort() else: sub_vertex = range(self.MG.user_num) g = self.graph.subgraph(sub_vertex, implementation="auto") node_list = self.node_list layout = g.layout_fruchterman_reingold() # layout = g.layout_circle() v_size_list = [] # 记录节点大小的列表 v_color_list = [] # 记录节点颜色的列表 v_label_list = [] # 记录标签名的列表 v_label_size = [] # 记录点标签的大小 for node_index in sub_vertex: v_size_list.append(800 * node_list[node_index].value + 13) v_label_size.append(300 * node_list[node_index].value + 8) if node_list[node_index].group == 0: v_color_list.append(color_dict[int(random.random() * 10000) % 52]) else: v_color_list.append( color_list[node_list[node_index].group % 7][node_list[node_index].influence - 1]) if node_list[node_index].influence < 2: v_label_list.append("") else: v_label_list.append( node_list[node_index].label.encode('utf-8')) p = igraph.Plot(bbox=(0, 0, 1000, 600)) p.background = "#f0f0f0" # 将背景改为白色,默认是灰色网格 p.add( g, layout=layout, # 图的布局 vertex_size=v_size_list, # 点的尺寸 edge_width=1, edge_arrow_size=0.8, # 箭头长度 edge_arrow_width=0.3, # 箭头宽度 edge_color="grey", # 边的颜色 vertex_label_size=v_label_size, # 点标签的大小 vertex_label=v_label_list, vertex_color=v_color_list, # 为每个点着色 margin=30 # 设置边缘 防止点画到图外 ) p.save(file_path) # 将图保存到特定路径 # p.show() p.remove(g) # 清除图像
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()
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()
def test_build_graph(self): manuel_graph = True if manuel_graph: specs = [[(8, 0), (1, 90), (1, 90), (6, 0), (1, 90), (8, 90), (0, 0)], [(1, 180), (0, 0), (0, 0), (1, 0), (0, 0), (1, 0), (0, 0)], [(8, 270), (1, 90), (1, 90), (2, 90), (1, 90), (2, 360), (0, 0)], [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (1, 0), (0, 0)], [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]] rail_shape = np.array(specs).shape env = rail_env.RailEnv( width=rail_shape[1], height=rail_shape[0], rail_generator=rail_generators. rail_from_manual_specifications_generator(specs), number_of_agents=1) else: env = rail_env.RailEnv( width=25, height=15, rail_generator=rail_generators.sparse_rail_generator()) observations, info = env.reset() tg = transition_graph.TransitionGraph(env) g = tg.g plt = igraph.Plot() layout = [(v['y'] + np.random.randn() * 0.125, v['x'] + np.random.randn() * 0.125) for v in g.vs] plt.add(g, layout=layout, margin=50, vertex_label=list(range(len(g.vs))), edge_label=list(range(len(g.es)))) plt.redraw() with tempfile.NamedTemporaryFile() as f: plt.save(f.name) graph_img = Image.open(f.name) render = rendertools.RenderTool(env, gl='PILSVG') render.render_env() bg_img = Image.fromarray(render.get_image()) graph_img.show( ) #uncomment for higher res graph images to inspect labels etc. minx, maxx, miny, maxy = min(g.vs['x']), max(g.vs['x']), min( g.vs['y']), max(g.vs['y']) envh, envw = env.height, env.width w, h = bg_img.size graph_img = graph_img.resize((int( (maxy - miny) / envw * w), int((maxx - minx) / envh * h))) bg_img = bg_img.resize( (int(w / envw * (envw + 1)), int(h / envh * (envh + 1)))) bg_img.paste(graph_img, (int(w / envw * (miny + .5)), int(h / envh * (minx + .5))), graph_img) bg_img.show() #import IPython #IPython.embed() print( f"edges that share common resources: {transition_graph.find_edges_that_share_resource(g)}" )
def test_build_graph(self): manuel_graph = True if manuel_graph: specs = [[(8, 0), (1, 90), (1, 90), (6, 0), (1, 90), (7, 90)], [(1, 180), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)], [(8, 270), (1, 90), (1, 90), (2, 90), (1, 90), (7, 90)], [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)], [(1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]] rail_shape = np.array(specs).shape env = rail_env.RailEnv( width=rail_shape[1], height=rail_shape[0], rail_generator=rail_generators. rail_from_manual_specifications_generator(specs), number_of_agents=1) else: env = rail_env.RailEnv( width=25, height=15, rail_generator=rail_generators.sparse_rail_generator()) observations, info = env.reset() #env = rail_env.RailEnv( # width=5, # height=5, # rail_generator=rail_generators.complex_rail_generator()) #obs, info = env.reset() #obs, info = env.reset() #obs, info = env.reset() tg = transition_graph.TransitionGraph(env) g = tg.g plt = igraph.Plot() layout = [(v['y'] + np.random.randn() * 0.15, v['x'] + np.random.randn() * 0.15) for v in g.vs] plt.add(g, layout=layout) plt.redraw() with tempfile.NamedTemporaryFile() as f: plt.save(f.name) graph_img = Image.open(f.name) render = rendertools.RenderTool(env, gl='PILSVG') render.render_env() bg_img = Image.fromarray(render.get_image()) graph_img = graph_img.resize(bg_img.size) minx, maxx, miny, maxy = min(g.vs['x']), max(g.vs['x']), min( g.vs['y']), max(g.vs['y']) envh, envw = env.height, env.width w, h = bg_img.size graph_img = graph_img.resize((int( (maxy - miny) / envw * w), int((maxx - minx) / envh * h))) bg_img = bg_img.resize( (int(w / envw * (envw + 1)), int(h / envh * (envh + 1)))) bg_img.paste(graph_img, (int(w / envw * (miny + .5)), int(h / envh * (minx + .5))), graph_img) bg_img.show()
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()
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
# initalize weights as if for all times g.es['weight'] = weights # change weights of hidden edges to 0 hidden_edges1['weight'] = 0 hidden_edges2['weight'] = 0 # visualization visual_style['edge_width'] = np.array(g.es['weight']) / 4 visual_style['edge_arrow_size'] = np.array(g.es['weight']) / 16 # 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