How can I get a graph of graphs to display in Sage? - networkx

I am working in SageMathCloud and have the following code:
import networkx
import matplotlib.pyplot as plt
test5 = networkx.Graph()
example = graphs.BuckyBall
test5.add_node(example)
networkx.draw(test5)
plt.show()
and from what I read, should display a graph with a single vertex that has a graph inside of it, like this picture from this article. However, all it shows is a single vertex with nothing inside of it as shown: Is there any way to display the graph to look like the 1st picture, where the graphs (as vertices) are shown?

Related

Add text for different part of line chart plot in plotly python

I draw a figure using plotly (python) as shown in below.
Now my aim is to show all points in same color but add different text for each colored part from this figure. For example, for the blue part I want to add the text AAA and for the red part BBB. How to do that in plotly?
I have simulated data with features that will generate a graph similar to one you have shown
there are three ways to add labels
labels against traces in legend
as additional scatter plots with mode="text"
as annotations on the figure
All three of these are demonstrated below. It does assume you have a working knowledge of pandas
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.DataFrame({"AAA":np.concatenate([np.random.uniform(1,5,20), np.full(20,np.nan)]),
"BBB":np.concatenate([np.full(20,np.nan), np.random.uniform(1,5,20), ])})
# create two traces, where traces are in legend to label AAA & BBB
fig = px.scatter(df, x=df.index, y=["AAA","BBB"]).update_traces(mode="lines+markers")
# additionally create text trace, that are last AAA & BBB
lastAAA = df.loc[~df["AAA"].isna()].iloc[-1]
lastBBB = df.loc[~df["BBB"].isna()].iloc[-1]
fig.add_trace(go.Scatter(x=[lastAAA.name], y=[lastAAA["AAA"]], text="AAA", mode="text", showlegend=False))
fig.add_trace(go.Scatter(x=[lastBBB.name], y=[lastBBB["BBB"]], text="BBB", mode="text", showlegend=False))
# additionally add annotations
fig.add_annotation(x=lastAAA.name, y=lastAAA["AAA"], text="AAA")
fig.add_annotation(x=lastBBB.name, y=lastBBB["BBB"], text="BBB")

how to create graph by edge and vertex txt file?

edge : vertex[coordinate]--vertex[coordinate]
how to feed the vertex and edge to a graph? I have tried by myself, but have problems.
import string
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph() # 建立一个空的无向图G
with open("HLN-12-1vertices.txt") as node_list:
for eachline in node_list:
G.add_node()
with open("HLN-12-1edges.txt") as edge_list:
for eachline in edge_list:
G.add_node()
print("number of edges:", G.number_of_edges()) # 输出边的数量
nx.draw(G)
plt.show()
First, you aren't actually passing the node name to the G.add_node parameter. If each line in your vertices text file has the name of the node, you can pass the variable eachline to the function (you might have to parse the file for end of line characters and other parsing if the file is formatted differently.
When you're reading the edges text file, the code again doesn't pass the edge data to the function, and you since you're passing the edge information, you need to use the function G.add_edge() instead. This function takes the parameters 'u_of_edge' and 'v_of_edge' which are the two endpoints of the edge.
Lastly, the function G.add_edge already adds new vertices to the graph if they aren't already created, so if all your vertices have an edge in the edges text file you can skip reading from the vertices text file.

ipython notebook read multiple images and display in CELL

How do I do the above ? This is my code but it doesn't work nothing is displayed
from PIL import Image
import glob
image_list = []
for filename in glob.glob('<my directory>.pgm'):
im=Image.open(filename)
image_list.append(im)
import matplotlib.pyplot as plt
for i in range(10):
plt.figure()
plt.imshow(image_list[i])
I would like it to be displayed in the cell
If you're interested in a much simpler and faster way of displaying images I recommend IPyPlot package:
import ipyplot
ipyplot.plot_images(images_list, max_images=20, img_width=150)
It's capable of displaying hundreds of images in a grid-like format within just 60-70ms
You would get a plot similar to this:
In your case, you should add %matplotlib inlinebefore your code and make sure that after plt.imshow(images_list) you add plt.show() as well so matplotlib renders your images.

Preserving Axis annotation while interactively zooming in on a matplotlib basemap plot?

I'm creating a figure displaying the worldmap with some data on it (which is irrelevant here). Now I want to be able to zoom in on it using the Pan/Zoom-button or the Zoom-to-rectangle-button and then save the figure to a picture file once I'm done zooming in. The problem is that the axis annotations (and the lng-/lat-lines) are "hard-embedded" in the picture, which make them vanish when you zoom in.
Does anybody know how to get axis annotations that adapt to the zooming?
Here is a minimal working example (without any data):
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
fig = plt.figure(1, figsize=(12, 7))
m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
llcrnrlon=-180,urcrnrlon=180,resolution='l') #,lat_ts=20
m.drawcoastlines(); m.fillcontinents(); m.drawcountries()
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,91.,30.),labels=[True, False, False, False], color='White')
m.drawmeridians(np.arange(-180.,181.,60.), labels=[False, False, False, True], color='White')
plt.show()
Just in case someone ever stumbles upon my question, here is what I came up with as a rather quick work-around. :-)
My intended application was to zoom in and then save the figure. Now I do not do that interactively but by entering the "zoomed bounding box" in the code and dynamically creating lng/lat-ticks with the following function (which needs an import numpy as np beforehand):
def calculateBasemapTicks(minMaxList, nrOfParalles = 3, nrOfMeridians = 3):
"""
Attempts to calculate meaningful ranges for .basemap.drawparallels
and .drawmeridians. Enter a <minMaxList> in the form
[lng_min, lng_max, lat_min, lat_max].
Note that you might get rather ugly floats. I suggest using formatting
as in ".drawparallels(..., fmt='%.4f')" or similar.
"""
pAdjust = (minMaxList[3]-minMaxList[2])*0.1
mAdjust = (minMaxList[1]-minMaxList[0])*0.1
parallels = np.linspace(minMaxList[2]+pAdjust,minMaxList[3]-pAdjust,
nrOfParalles)
meridians = np.linspace(minMaxList[0]+mAdjust,minMaxList[1]-mAdjust,
nrOfMeridians)
return parallels, meridians

Networkx: Importing graph with node values and edges information

I am generating random Geometric graph using networkx. I am exporting all the node and edges information into file.
I want to generate the same graph by importing all the node and edges information from file.
Code to export the node values and edge information.
G=nx.random_geometric_graph(10,0.5)
filename = "ipRandomGrid.txt"
fh=open(filename,'wb')
nx.write_adjlist(G, fh)
nx.draw(G)
plt.show()
I am trying to export it with below code and trying to change the color of some nodes. But it is generating different graph.
filename = "ipRandomGrid.txt"
fh=open(filename, 'rb')
G=nx.Graph()
G=nx.read_adjlist("ipRandomGrid.txt")
pos=nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b')
nx.draw(G)
plt.show()
How to generate the same graph with few changes in color of some nodes?
If I understand the problem you're having correctly, the trouble is here:
pos=nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b')
nx.draw(G)
You create a random layout of the graph in the first line, and use it to draw nodes '1' and '2' in the second line. You then draw the graph again in the third line without specifying the positions, which uses a spring model to position the nodes.
Your graph has no extra nodes, you've just drawn two of them in two different positions. If you want to consistently draw a graph the same way, you need to consistently use the pos you calculated. If you want it to be the same after storing and reloading, then save pos as well.
The easiest way to store node position data for your case might be using Python pickles. NetworkX has a write_gpickle() function that will do this for you. Note that the positions are already available as node attributes when you generate a random geometric graph so you probably want to use those when drawing. Here is an example of how to generate, save, load, and draw the same graph.
In [1]: import networkx as nx
In [2]: G=nx.random_geometric_graph(10,0.5)
In [3]: pos = nx.get_node_attributes(G,'pos')
In [4]: nx.draw(G,pos)
In [5]: nx.write_gpickle(G,'rgg.gpl')
In [6]: H=nx.read_gpickle('rgg.gpl')
In [7]: pos = nx.get_node_attributes(H,'pos')
In [8]: nx.draw(H,pos)