I'm was being able to generate MFCC from system captured audio and plot it, but after some refactor and configuring Tensorflow with CUDA. I used Librosa to generated the mfcc, matplotlib.pyplot with librosa.display to plot the MFCC and sounddevice capturing sound from Stereo mix from windows. The current configuration can create and plot MFCC from sample .wav files but when using system captured sounds it's not able to plot it since its generating a 3D array instead of a 2D when running MFCC. Here is the code that generates and plots
N_MFCC = 40
N_MELS = 40
N_FFT = 512
HOP_LENGTH = 160
MIN_FREQ = 0
MAX_FREQ = None
def create_mfcc(record, sample_rate):
features = librosa.feature.mfcc(record, sample_rate, n_fft=N_FFT,n_mfcc=N_MFCC,
n_mels=N_MELS,hop_length=HOP_LENGTH,fmin=MIN_FREQ, fmax=MAX_FREQ, htk=False)
return features
def plot_and_save_mfcc(mfcc_data, file_name, sample_rate):
plt.figure(figsize=(10, 8))
plt.title('Current audio MFCC', fontsize=18)
plt.xlabel('Time [s]', fontsize=18)
librosa_display.specshow(mfcc_data, sr=sample_rate)
plt.savefig(file_name)
plt.cla()
This generates this stack trace
Traceback (most recent call last):
File "main.py", line 68, in <module>
main()
File "main.py", line 63, in main
start_listening_and_creating_mfcc()
File "main.py", line 48, in start_listening_and_creating_mfcc
plot_and_save_mfcc(mfcc_data, conf.DEFAULT_MFCC_IMAGE_NAME.format(image_count), conf.SAMPLE_RATE)
File "main.py", line 38, in plot_and_save_mfcc
librosa_display.specshow(mfcc_data, sr=sample_rate)
File anaconda3\lib\site-packages\librosa\util\decorators.py", line 88, in inner_f
return f(*args, **kwargs)
File anaconda3\lib\site-packages\librosa\display.py", line 879, in specshow
out = axes.pcolormesh(x_coords, y_coords, data, **kwargs)
File anaconda3\lib\site-packages\matplotlib\__init__.py", line 1361, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 6183, in pcolormesh
X, Y, C, shading = self._pcolorargs('pcolormesh', *args,
File anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 5671, in _pcolorargs
nrows, ncols = C.shape
ValueError: too many values to unpack (expected 2)
I did try debug it and change mfcc configuration, but no success. Also did try to reconfigure my environment but this didn't help either.
EDIT: Here is the mfcc.Shapes for the System audio
(48000, 40, 1)
And for the .wav sample files
(40, 122)
As mentioned I left a function out of the question but here is it and the function the is used to load and create mfcc for the .wav files
def create_mfcc_from_file(file_path):
(signal, sample_rate) = librosa.load(file_path)
librosa_features = create_mfcc(signal, sample_rate)
plot_and_save_mfcc(librosa_features, 'mfcc-librosa', sample_rate)
def start_listening_and_creating_mfcc():
image_count = 0
while True:
my_recording = record_window()
mfcc_data = create_mfcc(my_recording, conf.SAMPLE_RATE)
plot_and_save_mfcc(mfcc_data, conf.DEFAULT_MFCC_IMAGE_NAME.format(image_count), conf.SAMPLE_RATE)
wav.write(conf.DEFAULT_MFCC_IMAGE_NAME.format(image_count) + '.wav', conf.SAMPLE_RATE, my_recording)
image_count += 1
def delta(feat, N):
"""Compute delta features from a feature vector sequence.
:param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector.
:param N: For each frame, calculate delta features based on preceding and following N frames
:returns: A numpy array of size (NUMFRAMES by number of features) containing delta features. Each row holds 1 delta feature vector.
"""
if N < 0:
raise ValueError('N must be an integer >0')
NUMFRAMES = len(feat)
denominator = 2 * sum([i**2 for i in range(1, N+1)])
delta_feat = numpy.empty_like(feat)
padded = numpy.pad(feat, ((N, N), (0, 0)), mode='edge') # padded version of feat
for t in range(NUMFRAMES):
delta_feat[t] = numpy.dot(numpy.arange(-N, N+1), padded[t : t+2*N+1]) / denominator
plt.plot(signal, c='c')# [t : t+2*N+1] == [(N+t)-N : (N+t)+N+1]
return delta_feat
Related
I am using deepgraph in python to compute correlation coefficients for large matrices. The output gives a multi-index data frame:
s t
0 1 -0.006066
2 0.094063
3 -0.025529
4 0.074080
5 0.035490
6 0.005221
7 0.032064
I want to add a column with corresponding p-values.
The original code with input example is obtained from https://deepgraph.readthedocs.io/en/latest/tutorials/pairwise_correlations.html
The code surrounded by hashtags is my approach to get p-values.
I want to merge the separate edge lists later on.
#!/bin/python
import os
from multiprocessing import Pool
import numpy as np
import pandas as pd
import deepgraph as dg
from numpy.random import RandomState
from scipy.stats import pearsonr, spearmanr
prng = RandomState(0)
n_features = int(5e3)
n_samples = int(1e2)
X = prng.randint(100, size=(n_features, n_samples)).astype(np.float64)
# Spearman's correlation coefficients
X = X.argsort(axis=1).argsort(axis=1)
# whiten variables for fast parallel computation later on
X = (X - X.mean(axis=1, keepdims=True)) / X.std(axis=1, keepdims=True)
# save in binary format
np.save('samples', X)
# parameters (change these to control RAM usage)
step_size = 1e5
n_processes = 100
# load samples as memory-map
X = np.load('samples.npy', mmap_mode='r')
# create node table that stores references to the mem-mapped samples
v = pd.DataFrame({'index': range(X.shape[0])})
# connector function to compute pairwise pearson correlations
def corr(index_s, index_t):
features_s = X[index_s]
features_t = X[index_t]
corr = np.einsum('ij,ij->i', features_s, features_t) / n_samples
return corr
#################################
def p_Val(index_s, index_t):
features_s = X[index_s]
features_t = X[index_t]
p = spearmanr(features_s, features_t)[1]
return p
#################################
# index array for parallelization
pos_array = np.array(np.linspace(0, n_features*(n_features-1)//2, n_processes), dtype=int)
# parallel computation
def create_ei(i):
from_pos = pos_array[i]
to_pos = pos_array[i+1]
# initiate DeepGraph
g = dg.DeepGraph(v)
# create edges
g.create_edges(connectors=corr, step_size=step_size, from_pos=from_pos, to_pos=to_pos)
# store edge table
g.e.to_pickle('tmp/correlations/{}_corr.pickle'.format(str(i).zfill(3)))
#################################
gp = dg.DeepGraph(v)
# create edges
gp.create_edges(connectors=p_Val, step_size=step_size, from_pos=from_pos, to_pos=to_pos)
# store edge table
gp.e.to_pickle('tmp/correlations/{}_pval.pickle'.format(str(i).zfill(3)))
#################################
# computation
if __name__ == '__main__':
os.makedirs("tmp/correlations", exist_ok=True)
indices = np.arange(0, n_processes - 1)
p = Pool()
for _ in p.imap_unordered(create_ei, indices):
pass
# store correlation values
files = os.listdir('tmp/correlations/')
files.sort()
for f in files:
et = pd.read_pickle('tmp/correlations/{}'.format(f))
print(et)
store.close()
I get the following error:
Traceback (most recent call last):
File "/lib/python3.9/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "pairwise_corr.py", line 64, in create_ei
gp.create_edges(connectors=p_Val, step_size=step_size, from_pos=from_pos, to_pos=to_pos)
File "/lib/python3.9/site-packages/deepgraph/deepgraph.py", line 616, in create_edges
self.e = _matrix_iterator(
File "/lib/python3.9/site-packages/deepgraph/deepgraph.py", line 4875, in _matrix_iterator
ei = _select_and_return(vi, sources_k, targets_k, ft_feature,
File "/lib/python3.9/site-packages/deepgraph/deepgraph.py", line 5339, in _select_and_return
ei = pd.DataFrame({col: data[col] for col in coldtypedic})
File "/lib/python3.9/site-packages/pandas/core/frame.py", line 614, in __init__
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
File "/lib/python3.9/site-packages/pandas/core/internals/construction.py", line 464, in dict_to_mgr
return arrays_to_mgr(
File "/lib/python3.9/site-packages/pandas/core/internals/construction.py", line 124, in arrays_to_mgr
arrays = _homogenize(arrays, index, dtype)
File "/lib/python3.9/site-packages/pandas/core/internals/construction.py", line 589, in _homogenize
val = sanitize_array(
File "/lib/python3.9/site-packages/pandas/core/construction.py", line 576, in sanitize_array
subarr = _sanitize_ndim(subarr, data, dtype, index, allow_2d=allow_2d)
File "/lib/python3.9/site-packages/pandas/core/construction.py", line 627, in _sanitize_ndim
raise ValueError("Data must be 1-dimensional")
ValueError: Data must be 1-dimensional
Any suggestions?
Thanks!
I was able to solve it with
def p_Val(index_s, index_t):
features_s = X[index_s]
features_t = X[index_t]
p = [pearsonr(features_s[i, :], features_t[i, :])[1] for i in range(len(features_s))]
p_val = np.asarray(p)
return p_val
I am using the Spyder IDE(5.3.3) with python(3.9.13 64bit) on Ubuntu 20.04LTS. I am trying to plot errorbar by calculating the standard deviation between '5' sets of data. My x-coordinate is named 'RC_AVG', y-coordinate is named 'PMF_AVG' and, the standard deviation is named 'PMF_STD'. After storing data in these lists, I've reshaped all of them to shape (175,1) and then I am using the ax.errorbar command to plot the errorbars but python throws 'Value error': 'yerr' (shape: (175, 1)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (175, 1)). I am unable to understand the cause of this error and need help in understanding it. However, when I remove the reshape(175,1) from the x,y and, the error coordinates the code works fine and I get the graph. I am attaching the code below:
typeimport numpy as np
import matplotlib.pyplot as plt
fig, (ax1) = plt.subplots(1,1,figsize=(5,5))
file_name = "bsResult-THETA83-IRUN"
result = []
for i in range(1,6):
a = np.array(np.loadtxt(file_name+str(i)+".xvg", dtype = float,skiprows=18,max_rows=175))
result.append(a)
result = np.array(result)
result1 = result.copy()
RC_AVG = np.mean(result1[:,:,0],axis=0).reshape(175,1) ###### x-coordinate
PMF_AVG = np.mean(result1[:,:,1],axis=0).reshape(175,1) ##### y-coordinate
PMF_STD = np.std(result1[:,:,2],axis=0).reshape(175,1) ###### error-coordinate
ax1.set_xlim(0.1,1.70)
ax1.set_xlabel("\u03B6 $(nm)$",fontweight = 'bold',fontsize=12)
ax1.set_ylabel("G $(k_{B}T)$",fontweight = 'bold',fontsize=12)
ax1.errorbar(RC_AVG,PMF_AVG,yerr=PMF_STD,label = 'Nitrogen',color='#D32D41',linewidth=1.0,elinewidth=1.0,
capsize=1.1,ecolor='black',errorevery=(8))
#####################################################################
Traceback (most recent call last):
File "/home/sps/software/yes/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
exec(code, globals, locals)
File "/media/sps/hdd/PMF/REFERENCE/pmf-2G6X6-epswdr-wspce-k400/pmfReference.py", line 31, in <module>
ax1.errorbar(RC_AVG,PMF_AVG,yerr=PMF_STD,label = 'Nitrogen',color='#D32D41',linewidth=1.0,elinewidth=1.0,
File "/home/sps/software/yes/lib/python3.9/site-packages/matplotlib/__init__.py", line 1423, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "/home/sps/software/yes/lib/python3.9/site-packages/matplotlib/axes/_axes.py", line 3588, in errorbar
raise ValueError(
ValueError: 'yerr' (shape: (175, 1)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (175, 1)) here
I am able to get the errorbars in the plot if I remove the reshape(175,1) from the x,y and, the error coordinates as shown below:
import matplotlib.pyplot as plt
fig, (ax1) = plt.subplots(1,1,figsize=(5,5))
file_name = "bsResult-THETA83-IRUN"
result = []
for i in range(1,6):
a = np.array(np.loadtxt(file_name+str(i)+".xvg", dtype = float,skiprows=18,max_rows=175))
result.append(a)
result = np.array(result)
result1 = result.copy()
RC_AVG = np.mean(result1[:,:,0],axis=0)#.reshape(175,1) ----commented reshape
PMF_AVG = np.mean(result1[:,:,1],axis=0)#.reshape(175,1) ---commented reshape
PMF_STD = np.std(result1[:,:,2],axis=0)#.reshape(175,1) ----commented reshape
ax1.set_xlim(0.1,1.70)
ax1.set_xlabel("\u03B6 $(nm)$",fontweight = 'bold',fontsize=12)
ax1.set_ylabel("G $(k_{B}T)$",fontweight = 'bold',fontsize=12)
ax1.errorbar(RC_AVG,PMF_AVG,yerr=PMF_STD,label = 'Nitrogen',color='#D32D41',linewidth=1.0,elinewidth=1.0,
capsize=1.1,ecolor='black',errorevery=(8))
type here
[enter image description here](https://www.stackoverflow.com/)
I'm attempting to follow this training example to calculate QG omega on NCEP/NCAR data but I'm getting hung up on mpcalc.advection().
It appears as if my dx and dy variables are a different shape, but I'm directly following the routine in an online example that supposedly works.
import numpy as np
import xarray as xr
import metpy.calc as mc
import metpy.constants as mpconstants
from metpy.units import units
# CONSTANTS
# ---------
sigma = 2.0e-6 * units('m^2 Pa^-2 s^-2')
f0 = 1e-4 * units('s^-1')
Rd = mpconstants.Rd
path = './'
uf = 'uwnd.2018.nc'
vf = 'vwnd.2018.nc'
af = 'air.2018.nc'
ads = xr.open_dataset(path+af).metpy.parse_cf()
uds = xr.open_dataset(path+uf).metpy.parse_cf()
vds = xr.open_dataset(path+vf).metpy.parse_cf()
a700 = ads['air'].metpy.sel(
level=700 * units.hPa,
time='2018-01-04T12')
u700 = uds['uwnd'].metpy.sel(
level=700 * units.hPa,
time='2018-01-04T12')
v700 = vds['vwnd'].metpy.sel(
level=700 * units.hPa,
time='2018-01-04T12')
lats = ads['lat'].metpy.unit_array
lons = ads['lon'].metpy.unit_array
X, Y = np.meshgrid(lons,lats)
dx, dy = mc.lat_lon_grid_deltas(lons,lats)
avort = mc.absolute_vorticity(u700, v700,
dx, dy, lats[:,None])
print('Array shape:', avort.shape)
print('DX shape:', dx.shape)
print('DY shape:', dy.shape)
print('U700 shape:', u700.shape)
print('V700 shape:', v700.shape)
vortadv = mc.advection(avort, (u700,v700), (dx,dy)).to_base_units()
Here's the error message, it also looks like I may have a unit issue?
Found lat/lon values, assuming latitude_longitude for projection grid_mapping variable
Found lat/lon values, assuming latitude_longitude for projection grid_mapping variable
Found lat/lon values, assuming latitude_longitude for projection grid_mapping variable
/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/metpy/calc/basic.py:1033: UserWarning: Input over 1.5707963267948966 radians. Ensure proper units are given.
'Ensure proper units are given.'.format(max_radians))
/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/pint/quantity.py:888: RuntimeWarning: invalid value encountered in true_divide
magnitude = magnitude_op(new_self._magnitude, other._magnitude)
Array shape: (73, 144)
DX shape: (73, 143)
DY shape: (72, 144)
U700 shape: (73, 144)
V700 shape: (73, 144)
Traceback (most recent call last):
File "metpy.decomp.py", line 56, in <module>
vortadv = mc.advection(avort, (u700,v700), (dx,dy)).to_base_units()
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/metpy/xarray.py", line 570, in wrapper
return func(*args, **kwargs)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/metpy/calc/kinematics.py", line 61, in wrapper
ret = func(*args, **kwargs)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/metpy/calc/kinematics.py", line 320, in advection
wind = _stack(wind)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/metpy/calc/kinematics.py", line 24, in _stack
return concatenate([a[np.newaxis] if iterable(a) else a for a in arrs], axis=0)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/metpy/calc/kinematics.py", line 24, in <listcomp>
return concatenate([a[np.newaxis] if iterable(a) else a for a in arrs], axis=0)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/dataarray.py", line 642, in __getitem__
return self.isel(indexers=self._item_key_to_dict(key))
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/dataarray.py", line 1040, in isel
indexers, drop=drop, missing_dims=missing_dims
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/dataset.py", line 2014, in _isel_fancy
name, var, self.indexes[name], var_indexers
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/indexes.py", line 106, in isel_variable_and_index
new_variable = variable.isel(indexers)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/variable.py", line 1118, in isel
return self[key]
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/variable.py", line 766, in __getitem__
dims, indexer, new_order = self._broadcast_indexes(key)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/variable.py", line 612, in _broadcast_indexes
return self._broadcast_indexes_outer(key)
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/variable.py", line 688, in _broadcast_indexes_outer
return dims, OuterIndexer(tuple(new_key)), None
File "/work1/jsa/anconda3/envs/earth/lib/python3.7/site-packages/xarray/core/indexing.py", line 410, in __init__
f"invalid indexer array, does not have integer dtype: {k!r}"
TypeError: invalid indexer array, does not have integer dtype: array(None, dtype=object)
Thanks in advance for any help!
So the problem is that in MetPy 1.0 the signature for advection changed, to be easier to use, to advection(scalar, u, v). Also, since you're working with Xarray data with MetPy 1.0, it can handle all of the coordinate stuff for you--you don't even need to deal with dx and dy manually:
subset = dict(level=700 * units.hPa, time='2018-01-04T12')
a700 = ads['air'].metpy.sel(**subset)
u700 = uds['uwnd'].metpy.sel(**subset)
v700 = vds['vwnd'].metpy.sel(**subset)
avort = mc.absolute_vorticity(u700, v700)
vortadv = mc.advection(avort, u700, v700).to_base_units()
We need to update that training example, but right now I'd recommend looking at the gallery examples 500 hPa Geopotential Heights, Absolute Vorticity, and Winds and 500 hPa Vorticity Advection.
I taught myself the Metropolis Algorithm and decided to try code it in Python. I chose to simulate the Ising model. I have an amateur understanding of Python and with that here is what I came up with -
import numpy as np, matplotlib.pyplot as plt, matplotlib.animation as animation
def Ising_H(x,y):
s = L[x,y] * (L[(x+1) % l,y] + L[x, (y+1) % l] + L[(x-1) % l, y] + L[x,(y-1) % l])
H = -J * s
return H
def mcstep(*args): #One Monte-Carlo Step - Metropolis Algorithm
x = np.random.randint(l)
y = np.random.randint(l)
i = Ising_H(x,y)
L[x,y] *= -1
f = Ising_H(x,y)
deltaH = f - i
if(np.random.uniform(0,1) > np.exp(-deltaH/T)):
L[x,y] *= -1
mesh.set_array(L.ravel())
return mesh,
def init_spin_config(opt):
if opt == 'h':
#Hot Start
L = np.random.randint(2, size=(l, l)) #lxl Lattice with random spin configuration
L[L==0] = -1
return L
elif opt =='c':
#Cold Start
L = np.full((l, l), 1, dtype=int) #lxl Lattice with all +1
return L
if __name__=="__main__":
l = 15 #Lattice dimension
J = 0.3 #Interaction strength
T = 2.0 #Temperature
N = 1000 #Number of iterations of MC step
opt = 'h'
L = init_spin_config(opt) #Initial spin configuration
#Simulation Vizualization
fig = plt.figure(figsize=(10, 10), dpi=80)
fig.suptitle("T = %0.1f" % T, fontsize=50)
X, Y = np.meshgrid(range(l), range(l))
mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu)
a = animation.FuncAnimation(fig, mcstep, frames = N, interval = 5, blit = True)
plt.show()
Apart from a 'KeyError' from a Tkinter exception and white bands when I try a 16x16 or anything above that, it looks and works fine. Now what I want to know is if this is right because -
I am uncomfortable with how I have used FuncAnimation to do the Monte Carlo simulation AND animate my mesh plot - does that even make sense?
And How about that cold start? All I am getting is a red screen.
Also, please tell me about the KeyError and the white banding.
The 'KeyError' came up as -
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 590, in callit
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 147, in _on_timer
TimerBase._on_timer(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1305, in _on_timer
ret = func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 1049, in _step
still_going = Animation._step(self, *args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 855, in _step
self._draw_next_frame(framedata, self._blit)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 873, in _draw_next_frame
self._pre_draw(framedata, blit)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 886, in _pre_draw
self._blit_clear(self._drawn_artists, self._blit_cache)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 926, in _blit_clear
a.figure.canvas.restore_region(bg_cache[a])
KeyError: <matplotlib.axes._subplots.AxesSubplot object at 0x7fd468b2f2d0>
You are asking a lot of questions at a time.
KeyError: cannot be reproduced. It's strange that it should only occur for some array sizes and not others. Possibly something is wrong with the backend, you may try to use a different one by placing those lines at the top of the script
import matplotlib
matplotlib.use("Qt4Agg")
white bands: cannot be reproduced either, but possibly they come from an automated axes scaling. To avoid that, you can set the axes limits manually
plt.xlim(0,l-1)
plt.ylim(0,l-1)
Using FuncAnimation to do the Monte Carlo simulation is perfectly fine. f course it's not the fastest method, but if you want to follow your simulation on the screen, there is nothing wrong with it. One may however ask the question why there would be only one spin flipping per time unit. But that is more a question on the physics than about programming.
Red screen for cold start: In the case of the cold start, you initialize your grid with only 1s. That means the minimum and maximum value in the grid is 1. Therefore the colormap of the pcolormesh is normalized to the range [1,1] and is all red. In general you want the colormap to span [-1,1], which can be done using vmin and vmax arguments.
mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu, vmin=-1, vmax=1)
This should give you the expected behaviour also for the "cold start".
I want to make a 2d histogramme by putting two 2D array as argument, Tx and alt_array, same size (56000,40)
def histo_2D(alt, Tx):
u,v = 56000,40
Tx = np.zeros((u,v))
alt_array = np.zeros((u,v))
alt,tx = np.zeros((v)), np.zeros((v))
for i in range(0,v):
alt[i] = i
tx[i] = i
alt_array[:][:] = alt
Tx[:][:] = tx
alt_array[:][:] = alt
print np.shape(Tx), np.shape(alt_array)
plt.hist2d(Tx , alt_array)
But when i try to execute my program, i get this error message :
Traceback (most recent call last):
File "goccp.py", line 516, in <module>
histo_2D(alt,Tx)
File "goccp.py", line 376, in histo_2D
plt.hist2d(Tx , alt_array)
File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2847, in hist2d
weights=weights, cmin=cmin, cmax=cmax, **kwargs)
File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 8628, in hist2d
normed=normed, weights=weights)
File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/twodim_base.py", line 650, in histogram2d
hist, edges = histogramdd([x, y], bins, range, normed, weights)
File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py", line 288, in histogramdd
N, D = sample.shape
ValueError: too many values to unpack
I've tried to use flattened array, but the result is not really good...
The documentation for hist2d states:
matplotlib.pyplot.hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, **kwargs)
Parameters: x, y: array_like, shape (n, ) :
Thus x and y need to be one dimensional; your values are two dimensional.
Have a look at the example as well, given at the end of the documentation.