I am trying to color the nodes in networkx according to node attributes, using a colormap. I was wondering how the middle point of the colormap could be set to zero?
This is an example code that I currently have:
import networkx as nx
from matplotlib import pyplot as plt
g=nx.Graph()
g.add_nodes_from(['A','B','C','D','E'])
g.add_edges_from([('A','B'),('B','C'),('B','D')])
nodes=g.nodes()
success_factor={'A':-1,'B':0,'C':7,'D':-2,'E':6}
nx.set_node_attributes(g, success_factor, 'success_factor')
success_color = [nx.get_node_attributes(g, 'success_factor')[v] for v in g]
pos=nx.spring_layout(g)
plt.figure()
ec = nx.draw_networkx_edges(g, pos=pos, alpha=0.8)
nc = nx.draw_networkx_nodes(g, pos=pos, nodelist=nodes, node_color=success_color, cmap=plt.cm.seismic)
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.05)
plt.colorbar(nc, cax=cax)
plt.show()
Related
How to draw parallel edges in the same direction?
import networkx as nx
import matplotlib.pyplot as plt
G = nx.MultiDiGraph()
G.add_node('A')
G.add_node('B')
G.add_edge('A', 'B', length = 1,key="1",label=1)
G.add_edge('A', 'B', length = 2,key="2",label=2)
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
The above code generates the following:
However, I want two edges with two labels.
I am trying to visualize this plot (from https://www.geeksforgeeks.org/matplotlib-figure-figure-show-in-python/). There is no error, but also no plot. What am I doing wrong?
Additional information: I suspect it has something to do with my Jupyter notebook settings, but I cannot find the right setting. I have tried several solutions including the tutorial here (https://www.tutorialspoint.com/jupyter/jupyter_notebook_plotting.htm)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500)
y = np.sin(x**2)+np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y, label ='Line 1')
ax.plot(x, y - 0.6, label ='Line 2')
ax.legend()
fig.suptitle("""matplotlib.figure.Figure.show()
function Example\n\n""", fontweight ="bold")
fig.show()
I'm new to python and matplotlib, and I'd like to visualise / compare 3 mfcc files stored as numpy arrays in txt format.
I have the Octave code below, and I'd like to know how it can be done using python/matplotlib.
Any help is much appreciated.
load /dir/k11.txt
load /dir/t11.txt
load /dir/a11.txt
subplot(1,2,1);imagesc(j11);axis('xy');colormap(jet);colorbar;subplot(1,2,2);imagesc(t11);axis('xy');colormap(jet);colorbar;
c=[k11(:,end),k11(:,1:end-1)];
figure(1);
Ncep=size(c,2)-1;
a=real(fft([c,zeros(size(c,1),512-Ncep*2-1),c(:,end:-1:2)]'));
imagesc(a(1:end/2,:));
axis('xy');
colormap(jet);
c=t11;
figure(2);
Ncep=size(c,2)-1;
a=real(fft([c,zeros(size(c,1),512-Ncep*2-1),c(:,end:-1:2)]'));
imagesc(a(1:end/2,:));
axis('xy');
colormap(jet);
c=a11;
figure(3);
Ncep=size(c,2)-1;
a=real(fft([c,zeros(size(c,1),512-Ncep*2-1),c(:,end:-1:2)]'));
imagesc(a(1:end/2,:));
axis('xy');
colormap(jet);
Obviously your example has externalities so I can't reproduce it directly, but in
general here is an octave example and its equivalent python one using the image features you require.
in Octave
% Read an image from a url
Url = 'https://raw.githubusercontent.com/utkuozbulak/singular-value-decomposition-on-images/master/data/grayscale_cat.jpg';
A = imread( Url );
imagesc( A ); % Show image in 'colour-scaled' form
axis xy % Reverse the origin of the y-axis
colormap( jet ); % Choose the jet colormap
in Python3
import urllib.request # needed for reading urls
import matplotlib.pyplot as plt # needed for imread/imshow
import matplotlib.colors as cl # needed for colour-scaling
# Read an image from a url
Url = urllib.request.urlopen( 'https://raw.githubusercontent.com/utkuozbulak/singular-value-decomposition-on-images/master/data/grayscale_cat.jpg' )
A = plt.imread( Url, 'jpg' )
plt.imshow( A, # Create a pyplot 'image' instance
norm = cl.Normalize(), # Choose colour-scaled form
origin = 'lower', # Reverse the origin of the y-axis
cmap = 'jet' # Choose the jet colormap
)
plt.show()
NetworkX has a decent code example for getting all the eigenvalues of a Laplacian matrix, given below:
import matplotlib.pyplot as plt
import networkx as nx
import numpy.linalg
n = 1000 # 1000 nodes
m = 5000 # 5000 edges
G = nx.gnm_random_graph(n, m)
L = nx.normalized_laplacian_matrix(G)
e = numpy.linalg.eigvals(L.A)
print("Largest eigenvalue:", max(e))
print("Smallest eigenvalue:", min(e))
plt.hist(e, bins=100) # histogram with 100 bins
plt.xlim(0, 2) # eigenvalues between 0 and 2
plt.show()
For the most part I follow all of this until you hit numpy.linalg.eigvals(L.A). What's the .A bit doing? I've looked at the documentation for sparse matrixes in SciPy, but I can't find a reference to this.
L.A is shorthand for L.toarray(). It is the matrix representation of the matrix object.
How to obtain the following surface via Matplotlib?
It is easy in matlab via:
mesh(peaks)
It seems matplotlib does not have an exact counterpart of mesh in matlab.
the Wireframe plots does not have any colormap option
While answering another question I found that you can easily do this using plot_surface to produce a color mapped surface, and then exchanging face and edge colors:
surf = ax.plot_surface(X, Y, Z, rstride=2, cstride=2, shade=False, cmap="jet", linewidth=1)
draw()
surf.set_edgecolors(surf.to_rgba(surf._A))
surf.set_facecolors("white")
show()
produces
The disadvantage this solution has over the other one is that the edges do not have smooth, per-pixel colouring, but one single color each.
It seems to be possible with matplotlib even if it is a bit of a hack:
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d import art3d
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
wire = ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
# Retrive data from internal storage of plot_wireframe, then delete it
nx, ny, _ = np.shape(wire._segments3d)
wire_x = np.array(wire._segments3d)[:, :, 0].ravel()
wire_y = np.array(wire._segments3d)[:, :, 1].ravel()
wire_z = np.array(wire._segments3d)[:, :, 2].ravel()
wire.remove()
# create data for a LineCollection
wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)])
wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)])
wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)])
to_delete = np.arange(0, nx*ny, ny)
wire_x1 = np.delete(wire_x1, to_delete, axis=1)
wire_y1 = np.delete(wire_y1, to_delete, axis=1)
wire_z1 = np.delete(wire_z1, to_delete, axis=1)
scalars = np.delete(wire_z, to_delete)
segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \
zip(wire_x1.T, wire_y1.T, wire_z1.T)]
# Plots the wireframe by a a line3DCollection
my_wire = art3d.Line3DCollection(segs, cmap="hsv")
my_wire.set_array(scalars)
ax.add_collection(my_wire)
plt.colorbar(my_wire)
plt.show()
An official feature request is underway:
https://github.com/matplotlib/matplotlib/issues/3562
The accepted solution doesn't work when X and Y arrays are not the same size.
It seems the current matplotlib 1.3.1 does not handle such mesh plot or further PDF export. gnuplot.pygnuplot.py 1.8 might be a choice before there is further updates in matplotlib.
Here is an example created via gnuplot:
MayaVI2 does not support PDF exports but might be another good choice.