Concatenate 3 different datasets for plot - python

I am currently having problem understanding how concatenating three numpy matrices can cause data to be changed. The three numpy matrices contains data for what should be shown in a spectogram.
static:
delta:
delta_delta:
but somehow when i concatenate them [static delta delta_delta] and make the same plot it looks like this:
why has the data set become corrupt in the last one?.. Here is how i concatenate and make the plots.
import os
import sys
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sb
import matplotlib
from matplotlib import cm
from PIL import Image
from python_speech_features import logfbank
from python_speech_features import delta
import scipy.io.wavfile as wav
import librosa
y,sr = librosa.load(fp,sr=16000) #fp being path to audio file
static_data = logfbank(y,sr,nfilt=13,preemph=0)
delta_data = delta(static_data,1)
delta_delta_data = delta(static_data,2)
output_hstacked = np.concatenate((static_data,delta_data,delta_delta_data),axis=0)
print output_hstacked.shape
Y = np.array(range(0,output_hstacked.shape[1]))
X = np.array(range(0,output_hstacked.shape[0]))
X,Y = np.meshgrid(X, Y)
plt.pcolormesh(X,Y,output_hstacked.T,cmap=cm.jet)
plt.xlabel('Frames(s)')
plt.ylabel('Frequency(Hz)')
plt.title('MFSS features of ' + filename)
#plt.yscale('log')
plt.colorbar()
#plt.show()
plt.savefig(spectogram_path_test+"/"+modified_name+"_stacked.png")
plt.close()
Y = np.array(range(0,static_data.shape[1]))
X = np.array(range(0,static_data.shape[0]))
X,Y = np.meshgrid(X, Y)
plt.pcolormesh(X,Y,static_data.T,cmap=cm.jet)
plt.xlabel('Frames(s)')
plt.ylabel('Frequency(Hz)')
plt.title('MFSS features of ' + filename)
#plt.yscale('log')
plt.colorbar()
#plt.show()
plt.savefig(spectogram_path_test+"/"+modified_name+"_static.png")
plt.close()
plt.pcolormesh(X,Y,delta_data.T,cmap=cm.jet)
plt.xlabel('Frames(s)')
plt.ylabel('Frequency(Hz)')
plt.title('MFSS features of ' + filename)
#plt.yscale('log')
plt.colorbar()
#plt.show()
plt.savefig(spectogram_path_test+"/"+modified_name+"_delta.png")
plt.close()
plt.pcolormesh(X,Y,delta_delta_data.T,cmap=cm.jet)
plt.xlabel('Frames(s)')
plt.ylabel('Frequency(Hz)')
plt.title('MFSS features of ' + filename)
#plt.yscale('log')
plt.colorbar()
#plt.show()
plt.savefig(spectogram_path_test+"/"+modified_name+"_delta_delta.png")
plt.close()
audio file can be found here

Related

Python, loop adds too many yticks in sublot

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

execute .py file, call python function in for loop

I have a function 'plot_rdm', which creates a plot and saves it as 'rdm.png'. I want several of these plots to be formed, each using a different .json file - so I have the function plot_rdm saved in 'plotrdm.py'.
In the saverdm.py file - I defined the filepath of the .json file I want to create a plot from and then called the plot_rdm function, looping over all of the files I want to create a plot from:
#import libraries
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import os
import json
# define fpath
#i.e. fpath[0] will be the first filepath...
path = './RDM_researchproject'
rootdir = path
filepath = []
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.startswith('Meadows'):
count=0 # count default
filepath.append(os.path.join(subdir, file))
fpath = filepath[count]
os.system("/home/taran/RDM_researchproject/AVIMA/plotrdm.py")
count +=1
The plotrdm.py file with the plot_rdm function is as follows:
def plot_rdm(fpath):
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import json
with open(fpath) as fhandle:
data = json.load(fhandle)
#inspect rdm stimuli labels
stim = data['stimuli']
#contain all labels for y axis and x axis seperately
y_names = []
for i in stim:
y_names.append(i['name'])
x_names = []
for i in stim:
x_names.append(i['name'])
#create rdm array and squareform
rdm_array = np.array(data['rdm'])
srdm = squareform(rdm_array)
#label x and y axis on rdm
fig, ax = plt.subplots()
rdm = ax.imshow(srdm)
ax.set_xticks(np.arange(len(x_names)))
ax.set_yticks(np.arange(len(y_names)))
ax.set_xticklabels(x_names)
ax.set_yticklabels(y_names)
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
plt.plot(srdm)
plt.imshow(srdm)
plt.colorbar(mappable = None, cax = None, ax = None)
fig.subplots_adjust(bottom=0.23)
import matplotlib.pyplot as plt
plt.savefig('rdm.png')
I am able to create the plots individually (i.e. when I don't call the plot_rdm function and loop over the files but I specify the filepath each time). But when I use the following code, I get an empty plot forming in the AVIMA folder. I'm not sure what's wrong in the saverdm file making this happen?
https://github.com/Taranks7/RDM_researchproject If I haven't explained what's going on well, this is the project I'm working on.
Thank you
When you want to call a python function from another file, you should not try to run another python process by calling os.system. Just import that function:
from plotrdm import plot_rdm
Instead of using os.filewalk and a file.startswith check, we can cleanup the code a lot by using the nice python library glob. I throw in a enumerate for good measure.
Your new rdmsave.py
import glob
from plotrdm import plot_rdm
basedir = "."
if __name__ == "__main__":
count = 0
for count, path in enumerate(sorted(glob.glob(f'{basedir}/**/Meadow*.json', recursive=True)), start=1):
print(f"processing {path}")
output_image = f'rdm_{count - 1:02}.png'
print(f"output image will be {output_image}")
plot_rdm(path, output_image)
print(f"processed {count} files")
Note that you may need to change basedir back to your local path.
And your plotrdm.py becomes:
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import json
import matplotlib.pyplot as plt
def plot_rdm(fpath, output_filename):
with open(fpath) as fhandle:
data = json.load(fhandle)
# inspect rdm stimuli labels
stim = data['stimuli']
# contain all labels for y axis and x axis seperately
y_names = []
for i in stim:
y_names.append(i['name'])
x_names = []
for i in stim:
x_names.append(i['name'])
# create rdm array and squareform
rdm_array = np.array(data['rdm'])
srdm = squareform(rdm_array)
# label x and y axis on rdm
fig, ax = plt.subplots()
rdm = ax.imshow(srdm)
ax.set_xticks(np.arange(len(x_names)))
ax.set_yticks(np.arange(len(y_names)))
ax.set_xticklabels(x_names)
ax.set_yticklabels(y_names)
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
plt.plot(srdm)
plt.imshow(srdm)
plt.colorbar(mappable=None, cax=None, ax=None)
fig.subplots_adjust(bottom=0.23)
plt.savefig(output_filename)
I added the second argument output_filename to the plot_rdm function to make it possible to store each image in a new file.
The output on my machine reads
processing ./5/Meadows_avima-image-version1_v_v2_vital-macaw_2_tree.json
output image will be rdm_00.png
processing ./4/Meadows_avima-image-version1_v_v2_quick-louse_2_tree.json
output image will be rdm_01.png
processing ./1/Meadows_avima-image-version1_v_v2_better-hound_2_tree.json
output image will be rdm_02.png
processing ./3/Meadows_avima-image-version1_v_v2_huge-falcon_2_tree.json
output image will be rdm_03.png
processing ./2/Meadows_avima-image-version1_v_v2_guided-koi_2_tree.json
output image will be rdm_04.png
processed 4 files
And 4 png files are created in the current folder.

time.sleep makes pictures in loop to not show

I've been trying to iterate over files in a folder and show them for two seconds each using this code:
import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import imread
import glob
import cv2
im = []
for filepath in glob.iglob(r'C:\Users\dan20\Pictures\wedding\beeri and adn. photo/*.jpg'):
a = imread(filepath)
b = cv2.resize(a, dsize = (456,304))
im += [b]
fig,ax = plt.subplots()
for i in im:
time.sleep(2)
ax.axis('off')
ax.imshow(i)
plt.show()
For some reason I can't see the images as long as i use time.sleep().
How can I make each picture to appear for N amount of times?
How about using plt.pause :
import numpy as np
from matplotlib import pyplot as plt
im = [np.random.random((9,9)) for i in range(1,6)]
fig,ax = plt.subplots()
for i in im:
ax.cla()
ax.imshow(i)
ax.axis('off')
plt.pause(2)
which gives :

I couldn't plot graph using matplotlib values from file

I want to plot ECG graph using matplotlib . y values from a file having float values and x value is incrementing(ie x ranges from 1 to 1000). went through tutorials and couldn't find any solutions.
Demo Code
import numpy as np
import matplotlib.pyplot as plt
import random
import pickle
#Y Axis : Generate 1000 random numbers
yAxisNumbers = np.random.uniform(1,100,1000)
#Save numbers to a file for demo purpose
with open('numpyData.txt', 'wb') as myFile:
pickle.dump(yAxisNumbers,myFile)
#X Axis :Generate 1000 random numbers
xNumbers = [ x for x in range(1000)]
#Load file data to a list
with open('numpyData.txt', 'rb') as aFile:
yNumbers = pickle.load(aFile)
#Plot and label Graph
plt.plot(xNumbers,yNumbers)
plt.ylabel("Random Float Numbers")
plt.xlabel("Number Count")
plt.title("ECG Graph")
plt.show()
Graph
Here's a minimal answer, based on the scant details provided.
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
Y = np.loadtxt(filename, other needed options)
plt.plot(np.arange(len(Y))+1,Y)
import numpy as np
import pylab as p
aa=np.loadtxt('....your file ....')
x,y= aa.T # transpose data into 2 columns, assuming you have 2 columns
p.plot(x,y)
p.show()

How to make the histograms 'touch' in pylab?

So I made a program that does what I need, mainly plots histogram from my data, but I have a few issues with it:
Here's the program:
# -*- coding: cp1250 -*-
from __future__ import division
from numpy import *
from matplotlib import rc
from matplotlib.pyplot import *
import numpy as np
import matplotlib.pyplot as plt
data = loadtxt("mioni.txt", int)
nuz = len(data)
nsmp = 20
duz = int(nuz/nsmp)
L = []
for i1 in range(0,nsmp):
suma = 0
for i2 in range(0,duz):
suma += data[i1*duz+i2]
L.append(suma)
print L
plt.hist(L, 20, normed=1, facecolor='blue', alpha=0.75)
plt.xlabel('t(\mu s)')
plt.ylabel('Broj događaja')
plt.axis([0,10,0,300])
plt.grid(True)
plt.show()
EDIT: so I managed to deal with the ugly sums, but now my histograms don't work :(
Data is here: http://dropcanvas.com/kqjem
What's wrong? I get tons of errors and python crashes :\
The problem comes from having a discrete data set, it looks like you set the bins parameter to something that doesn't fit. Use the pylab.hist parameter histtype="stepfilled" to get them to touch without the lines. Here are a few examples:
import numpy as np
import pylab as plt
# Sample data
X1 = np.random.exponential(1.0,size=5000)
X2 = [int(z) for z in X1]
plt.subplot(221)
plt.hist(X1,bins=50)
plt.title('Continuous Data')
plt.subplot(222)
plt.hist(X2,bins=50)
plt.title('Discrete Data')
plt.subplot(223)
plt.hist(X2,histtype='stepfilled')
plt.title('Discrete Data Filled')
plt.show()
use numpy.histogram: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
or matplotlib.pyplot.hist: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
for example:
plt.hist(data, bins=20)

Categories