How do I make this figure show up in a Jupyter notebook? - jupyter

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()

Related

Visualise/compare numpy arrays from Matlab/Octave to matplotlib

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()

Set colormap midpoint with networkx

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()

Solving and Plot Equation in Python

I am kind of new to python. All I am trying to do is to solve for y and plot the function,
In other words, plug values for x and generate y.
y^10+y = x.
Please forgive my ignorance.
from numpy import *
from matplotlib.pyplot import plot, show
y = arange(-10, 10, 0.01) #get values between -10 and 10 with 0.01 step and set to y
x = y**10 + y #get x values from y
plot(x, y)
show()
Using the matplotlib and numpy library: http://scipy.org/
If you want to solve things, use sympy: https://github.com/sympy/sympy/wiki/Quick-examples

How to obtain 3D colored surface via Python?

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.

plotting large time series efficiently (matplotlib)

I'm trying to plot three time series on the same axes using matplotlib. Each time series has 10^6 data points. While I have no problem generating the figure, the PDF output is large and very slow to open in viewers. Aside from working in a rasterized format, or only plotting a subset of the time series, is there a way to get better graphical performance? I have tried "optimizing" in acrobat, and I have also had the same trouble with matlab.
The code is as follows:
import numpy as np
import matplotlib.pyplot as plt
data=np.loadtxt('data.txt')
idx = data[:,0]
y1 = data[:,1]
y2 = data[:,2]
y3 = data[:,3]
plt.rc('text', usetex=True)
plt.rc('font', size=16)
fig, ax = plt.subplots()
ax.plot(idx,y1,color='b',label=r'$y_1$',
linewidth=2.0,markersize=10,fillstyle='none')
ax.plot(idx,y2,color='g',label=r'$y_2$',
linewidth=2.0,markersize=10,fillstyle='none')
ax.plot(idx,y3,color='r',label=r'$y_3$',
linewidth=2.0,markersize=10,fillstyle='none')
plt.xlabel(r'Index')
plt.ylabel(r'Vales')
legend = ax.legend(loc='upper right',fontsize=16)
ax.set_xscale('log')
plt.savefig('fig1.pdf',bbox_inches='tight')
plt.show()