-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyNeuroPlot.py
More file actions
executable file
·1900 lines (1595 loc) · 81 KB
/
PyNeuroPlot.py
File metadata and controls
executable file
·1900 lines (1595 loc) · 81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
module to perform data visualization,
including PSTH, tuning curve, stats, decoding, spectrum analysis, connectivity, etc
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import mpl_toolkits
import pandas as pd
import numpy as np
import scipy as sp
from scipy import signal as sgn
import re
import warnings
import misc_tools
import df_ana
import PyNeuroData as pnd
import PyNeuroAna as pna
mpl.style.use('ggplot')
""" df (pandas DataFrame) related opeartions """
# from df_ana import GroupPlot, DfPlot
def SpkWfPlot(seg, sortcode_min =1, sortcode_max =100, ncols=None):
"""
Plot spk waveforms of a segment, one channel per axes, different sort codes are color coded
:param seg: neo blk.segment
:param sortcode_min: the min sortcode included in the plot, default to 1
:param sortcode_max: the max sortcode included in the plot, default to 1
:param ncols: number of columns in the subplot
:return: figure handle
"""
N_chan = max([item.annotations['channel_index'] for item in seg.spiketrains]) # ! depend on the frame !
if ncols is None:
nrows, ncols = AutoRowCol(N_chan)
else:
nrows = int(np.ceil(1.0 * N_chan / ncols))
# spike waveforms:
fig, axes2d = plt.subplots(nrows=nrows, ncols=ncols, sharex='all', sharey='all',
figsize=(8,6), squeeze=False)
plt.tight_layout()
fig.subplots_adjust(hspace=0.05, wspace=0.05)
axes1d = axes2d.ravel()
sortcode_color = {0: np.array([225, 217, 111]) / 255.0,
1: np.array([149, 196, 128]) / 255.0,
2: np.array([112, 160, 234]) / 255.0,
3: np.array([142, 126, 194]) / 255.0,
4: np.array([202, 66, 45]) / 255.0,
5: np.array([229, 145, 66]) / 255.0}
for i, axes in enumerate(axes1d):
plt.sca(axes)
plt.xticks([])
plt.yticks([])
plt.text(0.1, 0.8, 'C{}'.format(i + 1), transform=axes.transAxes)
try: # for differenet versions of matploblib
try:
h_axes_top.set_facecolor([0.98, 0.98, 0.98])
except:
h_axes_top.set_axis_bgcolor([0.98, 0.98, 0.98])
except:
pass
for i in range(len(seg.spiketrains)):
try:
cur_chan = int(re.match('Chan(\d*) .*', seg.spiketrains[i].name).group(1)) # ! depend on the naming !
cur_code = int(re.match('.* Code(\d*)', seg.spiketrains[i].name).group(1)) # ! depend on the naming !
except:
cur_chan = i
cur_code = 0
print (misc_tools.red_text('the segment does not contain name like "Chan1 Code2"'))
if sortcode_min <= cur_code < sortcode_max:
axes_cur = axes1d[cur_chan - 1]
plt.sca(axes_cur)
h_text = plt.text(0.4, 0.12 * cur_code, 'N={}'.format(len(seg.spiketrains[i])), transform=axes_cur.transAxes, fontsize='smaller')
h_waveform = plt.plot(np.squeeze(np.mean(seg.spiketrains[i].waveforms, axis=0)))
if cur_code >= 0 and cur_code <= 5:
h_waveform[0].set_color(sortcode_color[cur_code])
h_text.set_color(sortcode_color[cur_code])
axes.set_ylim( np.max(np.abs(np.array(axes.get_ylim())))*np.array([-1,1]) ) # make y_lim symmetrical
fig.suptitle('spike waveforms, y_range={} uV'.format(np.round(np.diff(np.array(axes.get_ylim())) * 1000000)[0] ))
return fig
def ErpPlot_singlePanel(erp, ts=None, tf_inverse_color=False, tf_inverse_updown=True, cmap='coolwarm', c_lim_style='diverge', trace_scale=1):
"""
ERP plot in a single panel, where trace and color plot are superimposed. ideal for ERP recorded with linear probe
:param erp: erp traces, [N_chan, N_ts]
:param ts: timestapes
:param tf_inverse_color: if inverse sign for color plot. Useful for CSD plot since minus "sink" are commonly plot as red
:return: None
"""
N,T = erp.shape
if ts is None:
ts= np.arange(T)
if c_lim_style == 'diverge':
scale_signal = np.nanmax(np.abs(erp))
center_signal = 0
c_min = -scale_signal
c_max = +scale_signal
else:
scale_signal = np.nanmax(erp)-np.nanmin(erp)
center_signal = np.nanmean(erp)
c_min = np.nanmin(erp)
c_max = np.nanmax(erp)
if tf_inverse_color:
erp_plot = -erp
else:
erp_plot = erp
plt.pcolormesh(center2edge(ts), center2edge(range(N)), erp_plot, cmap=cmap, vmin=c_min, vmax=c_max)
if tf_inverse_updown:
plt.plot(ts, ( -(erp-center_signal)/scale_signal/2*trace_scale+np.expand_dims(np.arange(N), axis=1)).transpose(), 'k', alpha=0.2) # add "-" because we later invert y axis
ax = plt.gca()
# ax.set_ylim(sorted(ax.get_ylim(), reverse=True))
ax.set_ylim([N-0.5, -0.5])
else:
plt.plot(ts, ((erp - center_signal) / scale_signal / 2 * trace_scale + np.expand_dims(np.arange(N), axis=1)).transpose(), 'k', alpha=0.2) # add "-" because we later invert y axis
ax = plt.gca()
# ax.set_ylim(sorted(ax.get_ylim(), reverse=True))
ax.set_ylim([N - 0.5, -0.5])
ax.invert_yaxis()
def ErpPlot(data, ts=None, array_layout=None, depth_linear=None, title="ERP", tlim=None):
"""
ERP (event-evoked potential) plot
:param array_erp: a 2d numpy array ( N_chan * N_timepoints ) or the original data object
:param ts: a 1d numpy array ( N_timepoints )
:param array_layout: electrode array layout:
* if None, assume linear layout,
* otherwise, use the the give array_layout in the format: {chan: (row, col)}
:param depth_linear: a list of depth
:param title: a string of title
:tlim: None (by default using the full data length) or a list of two elements
:return: figure handle
"""
if type(data) is np.ndarray:
array_erp = data
ch_list = np.arange(0,array_erp.shape[0])
else:
array_erp = np.mean(data['data'],axis=0).transpose()
ch_list = list(data['signal_info']['channel_index'])
[N_chan, N_ts] = array_erp.shape
if ts is None:
ts = np.arange(N_ts)
if array_layout is None: # if None, assumes linear layout
offset_plot_chan = (array_erp.max()-array_erp.min())/5
if depth_linear is None:
depth_linear = np.array(np.arange(array_erp.shape[0]), ndmin=2).transpose() * offset_plot_chan
array_erp_offset = (array_erp - depth_linear).transpose()
else:
depth_linear = np.array(depth_linear)
depth_scale = depth_linear.max()-depth_linear.min()
if depth_scale < 10**(-9):
depth_scale = 1
depth_linear = np.expand_dims(depth_linear, axis=1)
array_erp_offset = (array_erp / offset_plot_chan /15.0 * depth_scale - depth_linear).transpose()
name_colormap = 'rainbow'
cycle_color = plt.cm.get_cmap(name_colormap)(np.linspace(0, 1, N_chan))
h_fig, h_axes = plt.subplots(1,2, figsize=(9,6))
plt.axes(h_axes[0])
for i in range(N_chan):
plt.plot(ts, array_erp_offset[:,i], c=cycle_color[i]*0.9, lw=2)
try: # for differenet versions of matploblib
try:
h_axes_top.set_facecolor([0.95, 0.95, 0.95])
except:
h_axes_top.set_axis_bgcolor([0.95, 0.95, 0.95])
except:
pass
if tlim is None:
plt.xlim(ts[0], ts[-1])
else:
plt.xlim(tlim[0],tlim[1])
# plt.ylim( -(N_chan+2)*offset_plot_chan, -(0-3)*offset_plot_chan, )
plt.title(title)
plt.xlabel('time from event onset (s)')
plt.ylabel('Voltage (V)')
plt.axes(h_axes[1])
plt.pcolormesh(center2edge(ts), center2edge(np.arange(N_chan)+1) , np.array(array_erp), cmap=plt.get_cmap('coolwarm'))
color_max = np.max(np.abs(np.array(array_erp)))
plt.clim(-color_max, color_max)
if tlim is None:
plt.xlim(ts[0], ts[-1])
else:
plt.xlim(tlim[0],tlim[1])
plt.ylim( center2edge(np.arange(N_chan)+1)[0], center2edge(np.arange(N_chan)+1)[-1] )
plt.gca().invert_yaxis()
plt.title(title)
plt.xlabel('time from event onset (s)')
plt.ylabel('channel index')
else: # use customized 2D layout, e.g. GM32 array
text_props = dict(boxstyle='round', facecolor='w', alpha=0.5)
[h_fig, h_axes] = create_array_layout_subplots(array_layout, tf_linear_indx=False)
plt.tight_layout()
h_fig.subplots_adjust(hspace=0.02, wspace=0.02)
h_fig.set_size_inches([8, 8],forward=True)
for ch in range(N_chan):
plt.axes(h_axes[array_layout[ch_list[ch]]])
plt.plot(ts, array_erp[ch, :], linewidth=2, color='dimgray')
plt.text(0.1, 0.8, 'C{}'.format(ch_list[ch]), transform=plt.gca().transAxes, fontsize=10, bbox=text_props)
if tlim is None:
plt.xlim(ts[0], ts[-1])
else:
plt.xlim(tlim[0],tlim[1])
# axis appearance
if False:
for ax in h_axes.flatten():
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
if len(ax.lines)==0:
try: # for differenet versions of matploblib
try:
h_axes_top.set_facecolor([1,1,1,0])
except:
h_axes_top.set_axis_bgcolor([1,1,1,0])
except:
pass
ax_bottomleft = h_axes[-1,0]
plt.axes(ax_bottomleft)
ax_bottomleft.get_xaxis().set_visible(True)
ax_bottomleft.get_yaxis().set_visible(True)
ax_bottomleft.set_xlabel('time')
ax_bottomleft.set_ylabel('Voltage')
plt.locator_params(axis='x', nbins=4)
plt.locator_params(axis='y', nbins=4)
ylim_max = np.max(np.abs(ax_bottomleft.get_ylim()))
ax_bottomleft.set_ylim([-ylim_max, ylim_max])
plt.suptitle(title, fontsize=18)
return h_fig, h_axes
def RfPlot(data_neuro, indx_sgnl=0, data=None, t_focus=None, tlim=None, tf_scr_ctr=False,
psth_overlay=True, t_scale=None, fr_scale=None, sk_std=None ):
"""
plot RF using one single plot
:param data_neuro: the data_neuro['cdtn'] contains 'x' and 'y', which represents the location of stimulus
:param indx_sgnl: index of signal, i.e. the data_neuro['cdtn'][:,:,indx_sgnl] would be used for plotting
:param data: if not None, use the data instead of data_neuro['data'][:,:,indx_sgnl], a 2D array of shape [N_trials, N_ts]
:param t_focus: duration of time used to plot heatmap, e.g. [0.050, 0.200]
:param tlim: duration of time used to plot psth overlay, e.g. [0.050, 0.200]
:param tf_scr_ctr: True/False, plot [0.0] point of screen
:param psth_overlay:True/False overlay psth
:param t_scale: for psth overlay, duration of time (ts) to be mapped to unit 1 of space
:param fr_scale: for psth overlay, scale for firing rate
:param sk_std: smooth kernel standard deviation, e.g. 0.005, for 5ms
:return:
"""
if data is None:
data = data_neuro['data'][:,:,indx_sgnl]
else:
data = data[:, :, indx_sgnl]
ts = np.array(data_neuro['ts'])
if sk_std is not None:
data = pna.SmoothTrace(data=data, sk_std=sk_std, ts=ts)
if t_focus is None:
t_focus = ts[[0,-1]]
if tlim is not None:
data = data[:,np.logical_and(ts>=tlim[0],ts<tlim[1])]
ts = ts[np.logical_and(ts>=tlim[0],ts<tlim[1])]
# get x and y values
x_grid = np.unique(np.array(data_neuro['cdtn'])[:,0])
y_grid = np.unique(np.array(data_neuro['cdtn'])[:,1])
x_spacing = np.mean(np.diff(x_grid))
y_spacing = np.mean(np.diff(y_grid))
if t_scale is None:
t_scale = ( ts[-1] - ts[0] )/x_spacing*1.1
fr_2D = np.zeros([len(x_grid),len(y_grid)])
for i, xy in enumerate(data_neuro['cdtn']):
x,y = xy
i_x = np.flatnonzero(x_grid == x)[0]
i_y = np.flatnonzero(y_grid == y)[0]
fr_2D[i_x, i_y] = np.mean( data[ data_neuro['cdtn_indx'][data_neuro['cdtn'][i]] , np.argwhere(np.logical_and(ts>=t_focus[0], ts<t_focus[1])) ])
if fr_scale is None:
fr_scale = np.nanmax(fr_2D) / y_spacing *2
if psth_overlay:
# plt.figure()
plt.title(data_neuro['signal_info']['name'][indx_sgnl])
plt.pcolormesh( center2edge(x_grid), center2edge(y_grid), fr_2D.transpose(), cmap='inferno')
for i, xy in enumerate(data_neuro['cdtn']):
plt.fill_between(xy[0] - x_spacing/2 + (ts-ts[0]) / t_scale, xy[1] - y_spacing/2,
xy[1] - y_spacing/2 + np.mean( data[data_neuro['cdtn_indx'][data_neuro['cdtn'][i]], :], axis=0) / fr_scale,
color='deepskyblue', alpha=0.5)
# plt.fill_between( xy[0]+np.array(data_neuro['ts'])/t_scale, xy[1], xy[1]+np.mean( data_neuro['data'][ data_neuro['cdtn_indx'][data_neuro['cdtn'][i]] ,:,indx_sgnl], axis=0 )/fr_scale, color=[0,0,0,0.5] )
# plt.plot(xy[0],xy[1],'r+', linewidth=1)
plt.xlim(center2edge(x_grid)[[0, -1]])
plt.ylim(center2edge(y_grid)[[0, -1]])
plt.axis('equal')
else:
plt.pcolormesh(center2edge(x_grid), center2edge(y_grid), fr_2D.transpose(), cmap='inferno')
if tf_scr_ctr:
plt.plot(x_grid[[0,-1]], [0,0], 'w-', Linewidth=0.5)
plt.plot([0,0], y_grid[[0,-1]], 'w-', Linewidth=0.5)
return fr_2D
def CreateSubplotFromGroupby(df_groupby_ord, figsize=None, tf_title=True, nrow=None, ncol=None):
"""
creates subplots according to the structure defined in df_ana.dfGropuby
:param df_groupby_ord: dictionary returned by df_ana.dfGroupby,
{'idx': {group_key: array of trial indexes within group}, 'order': {group_key: order in plot}}
:param figsize: e.g (12, 9)
:param tf_title: True/False to add title
:return: h_fig, h_axes
"""
if len(df_groupby_ord) == 0:
raise Exception('input dictionary can not be empty')
elif isinstance(list(df_groupby_ord.values())[0], int): # input is {str/num: int}, e.g. {'a': 0, 'b': 1}
N = max(df_groupby_ord.values())+1
num_r, num_c = AutoRowCol(N, nrow=nrow, ncol=ncol)
h_fig, h_axes = plt.subplots(num_r, num_c, sharex='all', sharey='all', squeeze=False, figsize=figsize)
h_axes = np.ravel(h_axes)
h_axes = {key: h_axes[val] for key, val in df_groupby_ord.items()}
else: # input is {tuple_of_cdtn: tuple_of_order}, e.g. {('a',1): (0,0), ('b',1): (1,1)}
Ns = list(map(lambda a: max(a)+1, zip(*df_groupby_ord.values())))
if len(Ns)==1:
h_fig, h_axes = plt.subplots(Ns[0], 1, sharex='all', sharey='all', squeeze=False, figsize=figsize)
h_axes = {key: h_axes[val][0] for key, val in df_groupby_ord.items()}
elif len(Ns)==2:
h_fig, h_axes = plt.subplots(Ns[0], Ns[1], sharex='all', sharey='all', squeeze=False, figsize=figsize)
h_axes = {key: h_axes[val] for key, val in df_groupby_ord.items()}
else:
raise Exception('val can not be more than two dimensions in input {key: val}')
if tf_title:
for key in h_axes:
plt.axes(h_axes[key])
plt.title(str(key))
return h_fig, h_axes
def PlotDataFromGroup(cdtn, data, plotfun=None):
"""
"""
if 'cdtn' in cdtn.keys(): # if input cdtn is data_neuro
cdtn = cdtn['cdtn']
figsize = [12, 9]
if isSingle(cdtn[0]): # if cdtn is 1D, automatically decide row and column
N_cdtn = len(cdtn)
[n_rows, n_cols] = AutoRowCol(N_cdtn)
[h_fig, h_ax]= plt.subplots(n_rows, n_cols, sharex='all', sharey='all', figsize=figsize) # creates subplots
h_ax = np.array(h_ax).flatten()
for i, cdtn_i in enumerate(cdtn):
plt.axes(h_ax[i])
if (plotfun is not None) and (data is not None): # in each panel, plot
plotfun(data[i])
plt.title(cdtn_i)
elif len(cdtn[0]) == 2: # if cdtn is 2D, use dim10 as rows and dim1 as columns
[cdtn0, cdtn1] = zip( *cdtn )
cdtn0 = list(set(cdtn0))
cdtn1 = list(set(cdtn1))
n_rows = len(cdtn0)
n_cols = len(cdtn1)
[h_fig, h_ax] = plt.subplots(n_rows, n_cols, sharex='all', sharey='all', figsize=figsize) # creates subplots
for i, cdtn_i in enumerate(cdtn):
r = cdtn0.index(cdtn_i[0])
c = cdtn1.index(cdtn_i[1])
plt.axes(h_ax[r, c])
if (plotfun is not None) and (data is not None): # in each panel, plot
plotfun(data[i])
plt.title(cdtn_i)
else: # if cdtn is more than 2D, raise exception
raise Exception('cdtn structure does not meet the requirement of PlotDataFromGroup')
try:
c_lim = share_clim(h_ax)
except:
warnings.warn('share clim was not successful')
return [h_fig, h_ax]
def SmartSubplot(data_neuro, functionPlot=None, dataPlot=None, suptitle='', tf_colorbar=False):
"""
Smart subplots based on the data_neuro['cdtn']
in each panel, plot using function 'functionPlot', on data 'dataPlot';
if cdtn is 1D, automatically decide row and column; if 2D, use dim0 as rows and dim1 as columns
:param data_neuro: dictionary containing field 'cdtn' and 'cdtn_indx', which directing the subplot layout
:param functionPlot: the plot function in each panel
:param dataPlot: the data that plot function applies on; in each panel, its first dim is sliced using data_neuro['cdtn_indx'], if None, use data_neuro[data]
:return: [h_fig, h_ax]
"""
if 'cdtn' not in data_neuro.keys(): # if the input data does not contain the field for sorting
raise Exception('data does not contain fields "cdtn" for subplot')
if ('data' in data_neuro.keys()) and dataPlot is None: # if dataPlot is None, use data_neuro[data]
dataPlot = data_neuro['data']
if isSingle(data_neuro['cdtn'][0]): # if cdtn is 1D, automatically decide row and column
N_cdtn = len(data_neuro['cdtn'])
[n_rows, n_cols] = AutoRowCol(N_cdtn)
[h_fig, h_ax]= plt.subplots(n_rows, n_cols, sharex=True, sharey=True) # creates subplots
h_ax = np.array(h_ax).flatten()
for i, cdtn in enumerate(data_neuro['cdtn']):
plt.axes(h_ax[i])
if (functionPlot is not None) and (dataPlot is not None): # in each panel, plot
functionPlot(dataPlot.take(data_neuro['cdtn_indx'][cdtn], axis=0))
plt.title(cdtn)
elif len(data_neuro['cdtn'][0])==2: # if cdtn is 2D, use dim10 as rows and dim1 as columns
[cdtn0, cdtn1] = zip( *data_neuro['cdtn'] )
cdtn0 = list(set(cdtn0))
cdtn1 = list(set(cdtn1))
n_rows = len(cdtn0)
n_cols = len(cdtn1)
[h_fig, h_ax] = plt.subplots(n_rows, n_cols, sharex=True, sharey=True) # creates subplots
for cdtn in data_neuro['cdtn']:
i = cdtn0.index(cdtn[0])
j = cdtn1.index(cdtn[1])
plt.axes(h_ax[i,j])
if (functionPlot is not None) and (dataPlot is not None): # in each panel, plot
functionPlot(dataPlot.take(data_neuro['cdtn_indx'][cdtn], axis=0))
plt.title(cdtn)
else: # if cdtn is more than 2D, raise exception
raise Exception('cdtn structure does not meet the requirement of SmartSubplot')
h_fig.set_size_inches([12,9], forward=True)
try:
plt.suptitle(suptitle.__str__() + ' ' + data_neuro['grpby'].__str__(), fontsize=16)
except:
pass
# share clim across axes
try:
c_lim = share_clim(h_ax)
except:
warnings.warn('share clim was not successful')
if tf_colorbar:
try:
h_fig.colorbar(plt.gci(), ax=h_ax.flatten().tolist())
except:
warnings.warn('can not create colorbar')
return [h_fig, h_ax]
def PsthPlot(data, ts=None, cdtn=None, limit=None, sk_std=None, subpanel='auto', color_style='discrete',
colors=None, linestyles=None, tf_legend=False, xlabel=None, ylabel=None, legend_title=None):
"""
funciton to plot psth with a raster panel on top of PSTH, works for both spike data and LFP data
:param data: neuro data, np array of various size and dtpye:
size: 2D [N_trials * N_ts] or 3D [N_trials * N_ts * N_signals]
dtype: boolean (spike exist or not) or float (LFP continuous values)
:param ts: 1D array containing timestamps for data (length is N_ts)
:param cdtn: conditions used to group
if data is 2D, represent the type of trials, len(cdtn)=N_ts
if data is 3D, represent the type of signals, len(cdtn)=N_signals
:param limit: index array to select a subset of the trials of data, i.e., data=data[limit,:]
:param sk_std: std of gaussian smoothness kernel, applied along time axis, default to None
:param subpanel: types of sub-panel on tops of PSTH, default to 'auto':
* if 'spk' : data2D is boolean, where every True value represents a spike, plot line raster
* if 'LFP' : data2D is continuous float, plot pcolormesh
* if 'auto' : use data format to decide which plot to use
* if '' : does not create subpanel
:param color_style: 'discrete' or 'continuous'
:param colors:
:param linestyles:
:param tf_legend: boolean, true/false to plot legend
:param x_label: string
:param y_label: string
:param legend_title:None or string
:return: axes of plot: [ax_psth, ax_raster]
"""
""" ----- process the input, to work with various inputs ----- """
if limit is not None: # select trials of interest
limit = np.array(limit)
data = data[limit]
cdtn_unq = None
if len(data.shape) == 3: # if data is 3D [N_trials * N_ts * N_signals]
[N,T,S] = data.shape
data2D = pnd.data3Dto2D(data) # re-organize as 2D [(N_trials* N_signals) * N_ts ]
if cdtn is None: # condition is the tag of the last dimension (e.g. signal name)
cdtn = np.array([[i]*N for i in range(S)]).ravel()
elif len(cdtn) == S:
cdtn_unq = np.array(cdtn)
cdtn = np.array([[i]*N for i in cdtn]).ravel()
else:
cdtn = ['']*(N*S)
warnings.warn('cdtn length does not match the number of signals in data')
elif len(data.shape) == 2: # if data is 2D [N_trials * N_ts]
data2D = data
[N, T] = np.shape(data2D)
if cdtn is None: # condition is the tag of the trials
cdtn = np.array(['']*N)
elif limit is not None:
cdtn = cdtn[limit]
else:
raise(Exception('input data does not have the right dimension'))
cdtn = np.array(cdtn)
if cdtn_unq is None:
cdtn_unq = get_unique_elements(cdtn) # unique conditions
M = len(cdtn_unq)
if ts is None:
ts = np.arange( np.size(data2D, axis=1) )
else:
ts = np.array(ts)
""" ----- calculate PSTH for every condition ----- """
ax_psth = plt.gca()
psth_cdtn = np.zeros([M, T])
N_cdtn = np.zeros(M).astype(int)
N_cdtn_cum = np.zeros(M+1).astype(int)
for k, cdtn_k in enumerate(cdtn_unq):
N_cdtn[k] = np.sum(cdtn==cdtn_k)
if N_cdtn[k] == 0:
psth_cdtn[k, :] = psth_cdtn[k, :]
else:
psth_cdtn[k, :] = np.mean(data2D[cdtn==cdtn_k], axis=0)
N_cdtn_cum[1:] = np.cumsum(N_cdtn)
if sk_std is not None: # condition for using smoothness kernel
ts_interval = np.diff(np.array(ts)).mean() # get sampling interval
kernel_std = sk_std / ts_interval # std in frames
kernel_len = int(np.ceil(kernel_std) * 3 * 2 + 1) # num of frames, 3*std on each side, an odd number
smooth_kernel = sgn.gaussian(kernel_len, kernel_std)
smooth_kernel = smooth_kernel / smooth_kernel.sum() # normalized smooth kernel
for k in range(M):
psth_cdtn[k, :] = np.convolve(psth_cdtn[k, :], smooth_kernel, 'same')
if colors is None:
colors = gen_distinct_colors(M, luminance=0.7, alpha=0.8, style=color_style)
""" ========== plot psth ========== """
hl_lines = []
for k, cdtn_k in enumerate(cdtn_unq):
if linestyles is None:
hl_line, = plt.plot(ts, psth_cdtn[k, :], c=colors[k])
else:
hl_line, = plt.plot(ts, psth_cdtn[k, :], c=colors[k], linestyle=linestyles[k])
hl_lines.append(hl_line)
textprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
plt.text(0.05, 0.9, 'N={}'.format(N), transform=ax_psth.transAxes,
verticalalignment='top', fontsize='x-small', bbox=textprops)
ax_psth.set_xlim([ts[0], ts[-1]])
if tf_legend:
plt.legend(cdtn_unq, labelspacing=0.1, prop={'size': 8},
fancybox=True, framealpha=0.5, title=legend_title)
if xlabel is not None:
plt.xlabel(xlabel)
if ylabel is not None:
plt.ylabel(ylabel)
""" ========== plot a subpanel, either rasters or LFP pcolor ========== """
if subpanel is not '':
# ========== sub-panel for raster or p-color ==========
ax_raster = add_axes_on_top(ax_psth, r=0.4)
plt.axes(ax_raster)
if subpanel == 'auto': # if auto, use the data features to determine raster (spk) plot or pcolor (LFP) plot
if len(np.unique(data2D)) <=20:
subpanel = 'spk'
else:
subpanel = 'LFP'
if subpanel is 'spk': # ---------- plot raster (spike trains) ----------
RasterPlot(data2D, ts=ts, cdtn=cdtn, colors=colors, max_rows=None, RasterType=subpanel)
elif subpanel is 'LFP': # ---------- plot_pcolor (LFP) ----------
RasterPlot(data2D, ts=ts, cdtn=cdtn, colors=colors, max_rows=None, RasterType=subpanel)
plt.setp(ax_raster.get_xticklabels(), visible=False)
else:
ax_raster = None
return [ax_psth, ax_raster]
def PsthPlotMultiPanel(data_neuro=None, index_signal=0,
data2D=None, ts=None, data_df=None,
limit=None, groupby_subplots='', aggregate_subplots=False,
linearize_subplots=False, nrow=None, ncol=None,
groupby_panel='', sk_std=None, subpanel='auto', color_style='discrete',
tf_legend=True, xlabel=None, ylabel=None, figsize=(12, 9), signal_name=''):
"""
plot PSTH in multiple subplots grouped by experimental conditions, a wrapper function of
pnp.PsthPlot, pnp.CreateSubplotFromGroupby and df_ana.DfGroupby,
data either provided by (data_neuro, index_signal) or (data2D, ts, data_df), the later one offers more control
:param data_neuro: standard data_neuro structure, retured by pnd.blk.align_to_event()
:param index_signal: index of signal used to select data_neuro['data'][:, :, index_signal]
:param data2D: neural data of one signal/channel, shape=[N_trials * N_ts]
:param ts: 1D array containing timestamps for data (length is N_ts)
:param data_df: pandas data frame of trial-related information, with num_rows=N_trials
:param limit: index array or boolean array, used to filter the trials that goes in the plot,
e.g. np.random.rand(N_trials)>0.5 or data_df['reaction_time']<500
:param groupby_subplots: column name(s) of data_df used to group data into subplots, either a str or a list of strings
:param aggregate_subplots: True/False to add a aggregation group (not grouped) for every column
:param linearize_subplots: column name of data_df used to group data within each panel
:param groupby_panel: column name of data_df used to group data within each panel
:param sk_std: std of gaussian smoothness kernel, applied along time axis, default to None
:param subpanel: types of sub-panel on tops of PSTH, default to 'auto'
:param color_style: 'discrete' or 'continuous'
:param tf_legend: boolean, true/false to plot legend
:param xlabel: string
:param ylabel: string
:param figsize: e.g. (12, 9)
:param signal_name: name of the signal to plot, shown in suptitle
:return:
"""
if data_neuro is not None:
if data2D is None:
data2D = data_neuro['data'][:, :, index_signal]
signal_name = data_neuro['signal_info']['name'][index_signal]
if ts is None:
ts = data_neuro['ts']
if data_df is None:
data_df = data_neuro['trial_info']
df_grpby = df_ana.DfGroupby(data_df, groupby=groupby_subplots, limit=limit,
tf_aggregate=aggregate_subplots, tf_linearize=linearize_subplots)
h_fig, h_axes = CreateSubplotFromGroupby(df_grpby['order'], figsize=figsize, nrow=nrow, ncol=ncol)
for cdtn in df_grpby['idx']:
plt.axes(h_axes[cdtn])
idx_trials = df_grpby['idx'][cdtn]
PsthPlot(data2D, ts=ts, cdtn=data_df[groupby_panel], limit=idx_trials,
sk_std=sk_std, subpanel=subpanel, color_style=color_style,
tf_legend=tf_legend, xlabel=xlabel, ylabel=ylabel, legend_title=groupby_panel,
)
plt.title(cdtn)
plt.suptitle('{}, grouped by {}'.format(signal_name, groupby_subplots))
return h_fig, h_axes
def RasterPlot(data2D, ts=None, cdtn=None, colors=None, RasterType='auto', max_rows=None):
"""
Spike/LFP raster Plot, where evary row presresent one trial, sorted by cdtn
:param data2D: 2D np.array of boolean/float values, [N_trial * N_ts]
:param ts: 1D np.array of timestamps, 1D np.array of length N_ts, used as x axis for plot
:param cdtn: condition of every trial, 1D np.array of length N_trial, used to sort trials
:param colors: a list of colors for every unique condition
:param RasterType: string, 'spk', 'LFP' or 'auto', default to 'auto':
* if 'spk' : data2D is boolean, where every True value represents a spike, plot line raster
* if 'LFP' : data2D is continuous float, plot pcolormesh
* if 'auto' : use data2D format to decide which plot to use
:return: handle of raster plot
"""
data2D = np.array(data2D)
[N, T] = data2D.shape
if cdtn is None: # if cdtn is none, fill with blank string
cdtn = ['']*N
# reorder index according to cdtn, so that trials of the same condition sits together in rows
cdtn_unq = get_unique_elements(cdtn)
M = len(cdtn_unq)
cdtn = np.array(cdtn)
index_reorder = np.concatenate([np.flatnonzero(cdtn == cdtn_k) for cdtn_k in cdtn_unq])
data2D = data2D[index_reorder,:]
cdtn = cdtn[index_reorder]
if colors is None: # if no color is given
colors = gen_distinct_colors(M, luminance=0.7)
if ts is None:
ts = np.arange(T)
# if N is too large, to speed up plot, randomly select a fraction to plot
if max_rows is not None:
if max_rows < N:
indx_subselect = np.sort(np.random.choice(N, max_rows, replace=False))
data2D = data2D[indx_subselect,:]
cdtn = cdtn[indx_subselect]
N = max_rows
if RasterType == 'auto':
if len(np.unique(data2D)) <= 20:
RasterType = 'spk'
else:
RasterType = 'LFP'
# color for every raster line
cdtn_indx_of_trial = np.zeros(N).astype(int)
N_cdtn = np.zeros(M).astype(int)
for k, cdtn_k in enumerate(cdtn_unq):
N_cdtn[k] = np.sum(cdtn == cdtn_k)
cdtn_indx_of_trial[cdtn == cdtn_k] = k
N_cdtn_cum = np.cumsum(N_cdtn)
if RasterType == 'spk':
if np.sum(data2D > 0) > 0 :
[y,x] = zip(*np.argwhere(data2D>0))
x_ts = ts[np.array(x)] # x loc of raster lines
y = np.array(y) # y loc of raster lines
y_min = y - 0.0005*N
y_max = y+1 +0.0005*N
c = np.array(colors)[ cdtn_indx_of_trial[np.array(y)] ]
# ----- major plot commmand -----
h_raster = plt.vlines(x_ts, y_min, y_max, colors=c, linewidth=2)
else:
h_raster = plt.vlines([], [], [])
elif RasterType == 'LFP':
# ----- major plot command -----
# c_axis_abs = np.max(np.abs(data2D))
c_axis_abs = np.percentile(np.abs(data2D), 98)
h_raster = plt.pcolormesh(center2edge(ts), range(N + 1), data2D, vmin=-c_axis_abs, vmax=c_axis_abs,
cmap=plt.get_cmap('coolwarm'))
# a colored line segment illustrating the conditions
if len(np.unique(cdtn))!=1:
plt.vlines(ts[[0] * M], np.insert(N_cdtn_cum, 0, 0)[0:M], N_cdtn_cum, colors=colors, linewidth=10)
else:
raise Exception('wrong RasterType, must by either "spk" or "LFP" ')
# horizontal lines deviding difference conditions
plt.hlines(N_cdtn_cum, ts[0], ts[-1], color='k', linewidth=1)
plt.xlim(ts[0],ts[-1])
plt.ylim(0, N)
plt.gca().invert_yaxis()
plt.yticks(keep_less_than([0]+N_cdtn_cum.tolist(), 8), fontsize='x-small')
return h_raster
def DataNeuroSummaryPlot(data_neuro, sk_std=None, signal_type='auto', suptitle='', xlabel='', ylabel='', tf_legend=False):
"""
Summary plot for data_neuro, uses SmartSubplot and PsthPlot
Use data_neuro['cdtn'] to sort and group trials in to sub-panels, plot all signals in every sub-panel
:param data_neuro: data_neuro structure, see moduel pnd.blk_align_to_evt
:param sk_std: smoothness kernel, if None, set automatically based on data type
:param signal_type: 'spk', 'LFP' or 'auto'
:param suptitle: title of figure
:param xlabel: xlabel
:param ylabel: ylabel
:return: figure handle
"""
ts = data_neuro['ts']
if signal_type == 'auto':
if len(np.unique(data_neuro['data'])) <=20: # signal is spk
signal_type = 'spk'
else:
signal_type = 'LFP' # signal is LFP
if sk_std is None:
if signal_type == 'spk':
sk_std = (ts[-1]-ts[0])/100
if xlabel =='':
xlabel = 't (s)'
if ylabel =='':
if signal_type == 'spk':
ylabel = 'firing rate (spk/s)'
elif signal_type == 'LFP':
ylabel = 'LFP (V)'
try:
name_signals = [x['name'] for x in data_neuro['signal_info']]
except:
name_signals = np.arange(data_neuro['data'].shape[2])
if 'cdtn' in data_neuro:
# plot function for every panel
functionPlot = lambda x: PsthPlot(x, ts=ts, cdtn=name_signals, sk_std=sk_std, tf_legend=tf_legend,
xlabel=xlabel, ylabel=ylabel, color_style='continuous')
# plot every condition in every panel
h = SmartSubplot(data_neuro, functionPlot, suptitle=suptitle)
else:
h = PsthPlot(data_neuro['data'], ts=ts, cdtn=name_signals, sk_std=sk_std, tf_legend=tf_legend,
xlabel=xlabel, ylabel=ylabel, color_style='continuous')
return h
def PsthPlotCdtn(data_neuro, data_df, i_signal=0, grpby='', fltr=[], sk_std=None, subpanel='', tf_legend=False):
""" Obsolete funciton """
data_neuro = pnd.neuro_sort(data_df, grpby=grpby, fltr=fltr, neuro=data_neuro)
ts = data_neuro['ts']
# plot function for every panel
functionPlot = lambda x: PsthPlot(x, ts=ts, sk_std=sk_std, tf_legend=tf_legend, color_style='continuous')
# plot every condition in every panel
h = SmartSubplot(data_neuro, functionPlot, dataPlot=data_neuro['data'][:,:,i_signal])
return h
def SpectrogramPlot(spcg, spcg_t=None, spcg_f=None, limit_trial = None,
tf_phase=False, tf_mesh_t=False, tf_mesh_f=False,
tf_log=False, time_baseline=None,
t_lim = None, f_lim = None, c_lim = None, c_lim_style=None, name_cmap=None,
rate_interp=None, tf_colorbar= False, quiver_scale=None, max_quiver=None):
"""
plot power spectrogram or coherence-gram, input spcg could be [ N_t * N*f ] or [ N_trial * N_t * N*f ], real or complex
:param spcg: 2D numpy array, [ N_f * N_t ] or 3D numpy array [ N_trial * N_f * N*t ], either real or complex:
* if [ N_trial * N_f * N*t ], average over trial and get [ N_f * N*t ]
* if complex, plot spectrogram using its abs value, and plot quiver using the complex value
:param spcg_t: tick of time, length N_t
:param spcg_f: tick of frequency, length N_f
:param limit_trial: index array to specify which trials to use
:param tf_phase: true/false, plot phase using quiver (spcg has to be complex): points down if negative phase (singal1 lags signal0 for coherence)
:param tf_mesh_t: true/false, plot LinemeshFlatPlot, focuse on t, (horizontal lines)
:param tf_mesh_f: true/false, plot LinemeshFlatPlot, focuse on f, (vertical lines)
:param tf_log: true/false, use log scale
:param c_lim_style: 'basic' (min, max), 'from_zero' (0, max), or 'diverge' (-max, max); default to None, select automatically based on tf_log and time_baseline
:param time_baseline: baseline time period to be subtracted, eg. [-0.1, 0.05], default to None
:param name_cmap: name of color map to use, default to 'inferno', if use diverge c_map, automatically change to 'coolwarm'; another suggested one is 'viridis'
:param rate_interp: rate of interpolation for plotting, if None, do not interpolate, suggested value is 8
:param tf_colorbar: true/false, plot colorbar
:return: figure handle
"""
if tf_log: # if use log scale
spcg = np.log(spcg * 10**6 + 10**(-32)) - 6 # prevent log(0) error
if limit_trial is not None:
spcg = spcg[limit_trial, :, :]
if spcg.ndim == 3: # if contains many trials, calculate average
spcg = np.mean(spcg, axis=0)
if np.any(np.iscomplex(spcg)): # if imaginary, keep the origianl and calculate abs
spcg_complex = spcg
spcg = np.abs(spcg)
else:
spcg_complex = None
if spcg_t is None:
spcg_t = np.arange(spcg.shape[1]).astype(float)
if spcg_f is None:
spcg_f = np.arange(spcg.shape[0]).astype(float)
# if use reference period for baseline, subtract baseline
if time_baseline is not None:
spcg_baseline = np.mean( spcg[:,np.logical_and(spcg_t >= time_baseline[0], spcg_t < time_baseline[1])],
axis=1, keepdims=True)
spcg = spcg - spcg_baseline
# set x, y limit
if t_lim is None:
t_lim = spcg_t[[0, -1]]
else:
tf_temp = np.logical_and(spcg_t>=t_lim[0], spcg_t<=t_lim[1])
spcg_t = spcg_t[tf_temp]
spcg = spcg[:, tf_temp]
if f_lim is None:
f_lim = spcg_f[[0, -1]]
else:
tf_temp = np.logical_and(spcg_f >= f_lim[0], spcg_f <= f_lim[1])
spcg_f = spcg_f[tf_temp]
spcg = spcg[tf_temp, :]
# set color limit
if c_lim is None:
if c_lim_style is None:
if time_baseline is not None: # if use reference period, symmetric about zero
c_lim_style = 'diverge'
else:
if (not tf_log) and (not np.any(spcg<0)): # if not log scale and no nagative values
c_lim_style = 'from_zero'
else: # otherwise, use basic
c_lim_style = 'basic'
if c_lim_style == 'diverge': # if 'deverge', set to [-a,a]
c_lim = [-np.max(np.abs(spcg)), np.max(np.abs(spcg))]
elif c_lim_style == 'from_zero': # if 'from zero', set to [0,a]
c_lim = [0, np.max(spcg)]
elif c_lim_style == 'basic': # otherwise, use 'basic', set to [a,b]
c_lim = [np.min(spcg), np.max(spcg)]
else:
c_lim = [np.min(spcg), np.max(spcg)]
warnings.warn('c_lim_style not recognized, must be "basic", "from_zero", "diverge", or None ')
if name_cmap is None:
if c_lim_style == 'diverge':
name_cmap = 'coolwarm' # use divergence colormap
else:
name_cmap = 'inferno' # default to inferno
if rate_interp is not None:
f_interp = sp.interpolate.interp2d(spcg_t, spcg_f, spcg, kind='linear')
spcg_t_plot = np.linspace(spcg_t[0], spcg_t[-1], (len(spcg_t)-1)*rate_interp+1 )
spcg_f_plot = np.linspace(spcg_f[0], spcg_f[-1], (len(spcg_f)-1)*rate_interp+1 )
spcg_plot = f_interp(spcg_t_plot, spcg_f_plot)
else:
spcg_t_plot = spcg_t
spcg_f_plot = spcg_f
spcg_plot = spcg
# plot using pcolormesh
h_plot = plt.pcolormesh(center2edge(spcg_t_plot), center2edge(spcg_f_plot),
spcg_plot, cmap=plt.get_cmap(name_cmap), shading= 'flat')
plt.xlim(t_lim)
plt.ylim(f_lim)
if c_lim is not None:
plt.clim(c_lim)
# color bar
if tf_colorbar:
plt.colorbar()
# quiver plot of phase: pointing down if negative phase, singal1 lags signal0 for coherence
if tf_phase is True and spcg_complex is not None:
try: # plot a subset of quivers, to prevent them from filling the whole plot
if max_quiver is None:
max_quiver = 32 # max number of quivers every dimension (in both axis)
if quiver_scale is None:
quiver_scale = 32 # about 1/32 of axis length
[N_fs, N_ts] = spcg.shape
indx_fs = np.array(keep_less_than(range(N_fs), max_quiver*1.0*(spcg_f.max()-spcg_f.min())/(f_lim[1]-f_lim[0])))
indx_ts = np.array(keep_less_than(range(N_ts), max_quiver))
plt.quiver(spcg_t[indx_ts], spcg_f[indx_fs],
spcg_complex[indx_fs, :][:, indx_ts].real, spcg_complex[indx_fs, :][:, indx_ts].imag,
color='r', units='height', pivot='mid', headwidth=5, width=0.005,
scale=np.percentile(spcg, 99.5) * quiver_scale)
except:
plt.quiver(spcg_t, spcg_f, spcg_complex.real, spcg_complex.imag,
color='r', units='height', pivot='mid', scale=np.percentile(spcg, 99.8) * quiver_scale)
if tf_mesh_t:
LinemeshFlatPlot(spcg_plot, spcg_t_plot, spcg_f_plot, N_mesh=16, axis_mesh='x')
if tf_mesh_f:
LinemeshFlatPlot(spcg_plot, spcg_t_plot, spcg_f_plot, N_mesh=16, axis_mesh='y')
plt.sci(h_plot) # set the current color-mappable object to be the specrogram plot but not the quiver
return h_plot
def LinemeshFlatPlot(data, x_grid=None, y_grid=None, axis_mesh='x',
N_mesh=16, scale_mesh=1.0/8, color='dimgrey'):
"""
an alternative to pcolormesh, focuse on change along one dimension (x, or y)
:param data: 2D numpy array (num_y * num_x), like the imput to imshow
:param x_grid: 1D numpy array, num_x
:param y_grid: 1D numpy array, num_x
:param axis_mesh: 'x', or 'y', the change on which axis you are interested in
:param N_mesh: number of lines to plot (controls thinning)
:param scale_mesh: the scale of individual lines relative the axis limit
:param color: color of lines
:return: handles of the lines
"""
if x_grid is None:
x_grid = np.arange(data.shape[1])
if y_grid is None:
y_grid = np.arange(data.shape[0])
x_grid_2D = np.expand_dims(x_grid, 0)
y_grid_2D = np.expand_dims(y_grid, 1)
if axis_mesh == 'x':
factor_scale = 1.0*scale_mesh * np.abs(y_grid[-1]-y_grid[0]) / (np.nanmax(np.abs(data))-np.nanmin(np.abs(data)))