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.
Related
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 am processing Long term afib dataset - https://physionet.org/content/ltafdb/1.0.0/
When I test the 30s strips of this data, my model is not correcting predicting the signals. So I am trying to deal with noise in this dataset. Here how it looks
Here is the code to plot -
def plot_filter_graphs(data,xmin,xmax,order):
from numpy import sin, cos, pi, linspace
from numpy.random import randn
from scipy import signal
from scipy.signal import lfilter, lfilter_zi, filtfilt, butter
from matplotlib.pyplot import plot, legend, show, grid, figure, savefig,xlim
lowcut=1
highcut=35
nyq = 0.5 * 300
low = lowcut / nyq
high = highcut / nyq
b, a = signal.butter(order, [low, high], btype='band')
# Apply the filter to xn. Use lfilter_zi to choose the initial condition
# of the filter.
z = lfilter(b, a,data)
# Use filtfilt to apply the filter.
y = filtfilt(b, a, data)
y = np.flipud(y)
y = signal.lfilter(b, a, y)
y = np.flipud(y)
# Make the plot.
figure(figsize=(16,5))
plot(data,'b',linewidth=1.75)
plot(z, 'r--', linewidth=1.75)
plot( y, 'k', linewidth=1.75)
xlim(xmin,xmax)
legend(('actual',
'lfilter',
'filtfilt'),
loc='best')
grid(True)
show()
I am using butter band pass filter to filter the noise. I also checked with filtfilt and lfilt but that is also not giving good result.
Any suggestion, how noise can be removed so that signal accuracy is good and hense it can be used for model prediction
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.
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()
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.