Python, loop adds too many yticks in sublot - python

I am subplotting over a loop, but the output is really crappy. I think it's stacking each single yticks.
Image Output
I need to give the image a single y axis, that's why I'm saving y_max and y_min for each iteration.
import matplotlib.pyplot as plt
import scipy
from scipy.optimize import curve_fit
from matplotlib import rc
rc('text', usetex=True)
import numpy as np
import math
from ctypes import *
import sys
np.finfo(np.dtype("float64"))
correlation_elements = 5
y_mag_max = np.zeros(correlation_elements)
y_mag_min = np.zeros(correlation_elements)
for i in range (correlation_elements):
fig_correl = plt.figure("correlations")
fig_correl.suptitle('Correlations')
start = i
end = i+correlation_elements
energy_correl_array = np.linspace(start, end, correlation_elements)
ax_correl_1 = fig_correl.add_subplot(1, 1, 1)
correlation_x_axis = np.linspace(0, correlation_elements-1, correlation_elements)
ax_correl_1.plot(correlation_x_axis, energy_correl_array,'.', label=r'$beta$ = {val:}'.format(val=i))
y_mag_max[i] = np.max(energy_correl_array)
y_mag_min[i] = np.min(energy_correl_array)
#Plotting Correlations
fig_correl.legend()
y_max = np.max(y_mag_max)
y_min = np.min(y_mag_min)
ax_correl_1.set_ylim(y_min, y_max)
ax_correl_1.set_ylabel('Energy')
plt.show()

Related

Convert imshow spectrogram to image

I would like to save just the wavelet image (no ticks nor labels) shown here to a png file.
I tried to follow the solution posted here for saving a spectrogram plot, but this approach is not working for me.
This is what I get:
This is the code that I have used:
import librosa
import librosa.display
import os
import pywt
import matplotlib.pyplot as plt
import soundfile as sf
import skimage.io
from tftb.generators import anasing
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from ssqueezepy import cwt
from ssqueezepy.visuals import plot, imshow
# Set the path to the Binary Class dataset
fulldatasetpath = 'G:/AudioFile'
input_file = (r'G:/Audiofile.wav')
[data1, sample_rate1] = sf.read(input_file)
#[sample_rate1, data1] = wav.read(input_file);
duration = len(data1)/sample_rate1
time = np.arange(0, duration, 1/sample_rate1) #time vector
#%%############## Take CWT & plot ##################################################
Wx, scales = cwt(data1, 'morlet')
imshow(Wx, abs=1)
plt.show()
Wx = abs(Wx)
#%%############## SAVE TO IMAGE ###########################################
def scale_minmax(X, min=0.0, max=1.0):
X_std = (X - X.min()) / (X.max() - X.min())
X_scaled = X_std * (max - min) + min
return X_scaled
wave1 = np.log(Wx + 1e-9) # add small number to avoid log(0)
# min-max scale to fit inside 8-bit range
img = scale_minmax(Wx, 0, 255).astype(np.uint8)
img = np.flip(img, axis=0) # put low frequencies at the bottom in image
img = 255-img # invert. make black==more energy
out = 'out.png'
# save as PNG
skimage.io.imsave(out, img)
You can set the position of the axis to cover the entire figure, and you can also play with figsize. For example:
import matplotlib.pyplot as plt
import numpy as np
from ssqueezepy import imshow
# test image
img = np.zeros((500, 40000, 3), dtype=int)
for i in range(img.shape[1]):
img[:, i, 0] = int(abs(1 - 2 * i / img.shape[1]) * 255)
# create a figure and set the size
f = plt.figure(figsize=(8, 4))
# add a new axis into which ssqueezepy is going to plot
ax = f.add_subplot()
imshow(img)
# turn off tick labels
ax.axis(False)
# make the axis to cover the entire figure
ax.set_position([0, 0, 1, 1])
f.savefig("result.png")

Interpolation between 2d-data to create a 3d-surface?

I have several data rows from measurements with x/y-data which I would like to represent as a 2d-surface/3d-surface. For a short test I wrote the following demo script:
#!/usr/bin/env python3
import h5py
import numpy as np
from numpy.core.numeric import full
import scipy.constants as scco
from scipy.signal import butter, lfilter, freqz
from scipy.integrate import solve_ivp
import matplotlib
matplotlib.use('Qt5Cairo')
from matplotlib import pyplot as plt
from scipy import interpolate, optimize
from PIL import Image, PngImagePlugin
from os import listdir
from os.path import isfile, join
import math
from string import Template
import subprocess
import types
import functools
from enum import Enum
import sys
first_position = 2
second_position = 4
third_position = 6
x_vec = np.linspace(0, 10, 1024)
def gen_function(x_vec, f_pos, factor):
return np.exp(-np.power(x_vec - f_pos, factor))
first_vec = gen_function(x_vec, first_position, 32)
second_vec = gen_function(x_vec, second_position, 8)
third_vec = gen_function(x_vec, third_position, 2)
plt.plot(x_vec, first_vec)
plt.plot(x_vec, second_vec)
plt.plot(x_vec, third_vec)
plt.show()
ax = plt.subplot(1, 1, 1, projection="3d")
ax.plot(x_vec, np.ones(x_vec.size) * first_position * 0.1, first_vec)
ax.add_collection3d(plt.fill_between(x_vec, 0.95 * first_vec, 1.05 * first_vec, alpha=0.3), zs = first_position, zdir='y')
ax.plot(x_vec, np.ones(x_vec.size) * second_position * 0.1, second_vec)
ax.add_collection3d(plt.fill_between(x_vec, 0.95 * second_vec, 1.05 * second_vec, alpha=0.3), zs = second_position, zdir='y')
ax.plot(x_vec, np.ones(x_vec.size) * third_position * 0.1, third_vec)
ax.add_collection3d(plt.fill_between(x_vec, 0.95 * third_vec, 1.05 * third_vec, alpha=0.3), zs = third_position, zdir='y')
plt.show()
Here, x_vec represents my x-data from my measurements, and the vectors first_vec, second_vec and third_vec represent example y data. When executing it, I get
I would now like to find a way to interpolate the empty space in between, such that I either can have a 3d-surface plot instead, or reduce the data to a 2d-surface plot. What could I use for that?

The asymptotic series plot is empty

I'm trying to plot the graph for this asymptotic series a_k = -k!(-x)**(k+1), with x=8, for k = 0,1,2,3......20, but my graph has no points in it.
Here is my code.
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import factorial
k = np.linspace(0.0, 30.0, 10)
a_k = -factorial(k)*(-8)**(k+1)
plt.semilogy(k,a_k,'b-')
plt.xlabel("k")
plt.ylabel("a_k")
plt.title("Asymptotic series with x = 8")
plt.show()

How do you quantize a simple input using python

I am using the below codes to quantise the input signal for quantisation interval of 0.5 and this should give me staircase signal.The algorithm used here is same as used in Simulink.Could any one help me plot the quantised signal.
import numpy as np
import matplotlib.pyplot as plt
for i in range(0,10):
q=0.5;
x=q*np.round(i/q);
plt.plot(i,x)
plt.xlim([0,10])
plt.ylim([0,10])
plt.hold()
plt.grid()
plt.show()
Do you mean something like this?
import numpy as np
import matplotlib.pyplot as plt
q = 0.5
x = np.linspace(0, 10, 1000)
y = q * np.round(x/q)
plt.plot(x,y)

Matplotlib How to get length line

I use Matplotlib with Python 2.7.6 and my code
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline
x = np.array([1,2,3])
y = np.array([1,5,15])
x_smooth = np.linspace(x.min(), x.max(), 100)
y_smooth = spline(x, y, x_smooth)
plt.plot(x_smooth, y_smooth)
plt.show()
When I run it show image
How to get the length of Spline ? Help me
import math
distance = 0
for count in range(1,len(y_smooth)):
distance += math.sqrt(math.pow(x_smooth[count]-x_smooth[count-1],2) + math.pow(y_smooth[count]-y_smooth[count-1],2))
in cartesian geometry the distance between two points is calculated as
p1(x,y), p2(a,b)
[p1p2] = sqrt((a-x)^2 + (b-y)^2)
I'm sure there is a more elegant way to do this, probably in a one-liner

Categories