import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
from PIL import Image
Chapter 4b
Chapter 4b
Analyzing Neural Time Series Data
Python code for Chapter 4 script B – converted from original Matlab by AE Studio (and ChatGPT)
Original Matlab code by Mike X Cohen
This code accompanies the book, titled “Analyzing Neural Time Series Data” (MIT Press).
Using the code without following the book may lead to confusion, incorrect data analyses, and misinterpretations of results.
Mike X Cohen and AE Studio assume no responsibility for inappropriate or incorrect use of this code.
Import necessary libraries
Basic plotting
A library called matplotlib is often used for plotting. Note that the plots may function slightly differently in a Python script as compared to in IPython.
# Open a new figure and plot X by Y
plt.figure()range(1, 11), np.power(range(1, 11), 2))
plt.plot(
plt.show()
# Plots do not overwrite previous plots in IPython
range(1, 11), np.log(range(1, 11)))
plt.plot(
plt.show()
# Multiple plots in the same figure
range(1, 11), np.power(range(1, 11), 2), linewidth=3)
plt.plot(range(1, 11), np.log(range(1, 11)) * 30, 'r-d')
plt.plot(
plt.show()
# Drawing lines
range(1, 11), np.power(range(1, 11), 2), linewidth=3)
plt.plot(range(1, 11), np.log(range(1, 11)) * 30, 'r-d')
plt.plot(# Note that we have to plot the curves again unlike with MATLAB's `hold on`
2, 9], [60, 60], 'k')
plt.plot([1, 10], [0, 100], 'm:')
plt.plot([
plt.show()
# Plot something else
range(1, 11), np.multiply(range(1, 11), 3))
plt.plot(
plt.show()
# Plot information in variables
= np.arange(0, 1.1, 0.1)
x = np.exp(x)
y '.-')
plt.plot(x, y,
plt.show()
# x and y need to be of equal length
= np.arange(0, 1.1, 0.1)
x = np.array([0] + list(np.exp(x)))
y try:
'.-')
plt.plot(x, y,
plt.show()except ValueError as e:
print(e)
# Plot multiple lines simultaneously
range(100, 1001, 100), # You can add a break to continue the code on the next line. This is convenient for long lines of code that you want to be visible on a single screen without using the horizontal scrollbar.
plt.plot(10, 3))
np.random.rand('Random lines')
plt.title('x-axis label... maybe time? maybe space?')
plt.xlabel('voltage (μV)')
plt.ylabel('line 1', 'line 2', 'line 3'])
plt.legend([ plt.show()
x and y must have same first dimension, but have shapes (11,) and (12,)
Plotting lines in 3D space
# Define data in 3 dimensions
= 10
n = np.random.rand(n)
dataX = np.random.randn(n)
dataY = np.random.rand(n) * 10
dataZ
# Plot a line in 3D space
= plt.figure()
fig = fig.add_subplot(111, projection='3d')
ax
ax.plot(dataX, dataY, dataZ)True)
ax.grid(
# Adding other features to the plot
'X-axis')
ax.set_xlabel('Y-axis')
ax.set_ylabel('Z-axis')
ax.set_zlabel(
plt.show()
# Plotting a 3D matrix
= np.random.randn(3, 30)
data3d = plt.figure()
fig = fig.add_subplot(111, projection='3d')
ax 0, :], data3d[1, :], data3d[2, :], 'ko-', linewidth=3, markerfacecolor='m')
ax.plot(data3d['off')
ax.axis('square')
ax.axis( plt.show()
Slightly more advanced: get and set
# Plot and modify axis properties
range(1, 11), np.random.rand(10, 3))
plt.plot(= plt.gca()
ax range(1, 10, 2))
ax.set_xticks('one', 'three', 'five', 'seven', 'nine'])
ax.set_xticklabels([
# Get axis properties
= ax.get_ylim()
axis_ylim
# Assign axis properties using variables
= [-0.3, -np.cos(np.pi)]
the_ylim_i_want
ax.set_ylim(the_ylim_i_want)
plt.show()
# Change properties of figures
range(1, 11), np.random.randn(10, 3))
plt.plot(= plt.gcf() # Get current figure
fig = plt.gca() # Get current axis
ax 1, -1.5])
ax.set_ylim([5, 10])
ax.set_xlim([0.6, 0, 0.8))
fig.patch.set_facecolor(('Hello there')
plt.title(= ax.title
titleh 40)
titleh.set_fontsize('LARGE TITLE')
titleh.set_text(
# Draw lines showing the 0 crossings
0, 0], 'k')
plt.plot(ax.get_xlim(), [6, 6], ax.get_ylim(), 'k:')
plt.plot([ plt.show()
Subplots
# Use multiple plots in a figure
plt.figure()1, 2, 1)
plt.subplot(10, 2))
plt.plot(np.random.randn(1, 2, 2)
plt.subplot(10, 2))
plt.plot(np.random.randn(
plt.tight_layout()
plt.show()
# More subplots with different features
= ['r', 'g', 'm', 'k']
edgecolors
plt.clf()for subploti in range(1, 5):
2, 2, subploti)
plt.subplot(range(1, subploti + 1), np.multiply(range(1, subploti + 1), 2) + 1, 'm-p', linewidth=3, markeredgecolor=edgecolors[subploti - 1])
plt.plot(= plt.gca()
ax 0.5, 4.5])
ax.set_xlim([1, 10])
ax.set_ylim(['Subplot {}{}'.format(subploti, '!' * subploti))
plt.title(
plt.tight_layout() plt.show()
Basic image plotting
# Plot images in 2D
plt.figure()100, 100))
plt.imshow(np.random.randn(
plt.show()
# Imagesc with x, y, z inputs
100, 100))
plt.imshow(np.random.randn(0, 110, 10), np.round(np.arange(0, 1.1, 0.1), 1))
plt.yticks(np.arange(0, 110, 10))
plt.xticks(np.arange(
plt.show()
# Make the plot smoother with a 2D Gaussian convolution
= np.arange(-1, 1.1, 0.1)
xyrange = np.meshgrid(xyrange, xyrange)
X, Y = np.exp(-(X**2 + Y**2))
gaus2d
# Look at the Gaussian
plt.imshow(gaus2d)
plt.show()
# Convolve and plot
100, 100), mode='same'))
plt.imshow(convolve2d(gaus2d, np.random.randn(0, 22, 2), np.round(np.arange(-1, 1.1, 0.2), 1))
plt.yticks(np.arange(0, 22, 2), np.round(np.arange(-1, 1.1, 0.2), 1))
plt.xticks(np.arange(
plt.colorbar()
plt.show()
# Change the colormap
100, 100), mode='same'))
plt.imshow(convolve2d(gaus2d, np.random.randn(
plt.colorbar()'jet')
plt.set_cmap(
plt.show()
# Following plots will continue to use the 'jet' colormap unless we change it back to the default
'viridis')
plt.set_cmap(
# There are other functions you can use for 2D data, including:
plt.figure()= convolve2d(gaus2d, np.random.randn(100, 100), mode='same')
data 221)
plt.subplot(=(xyrange[0], xyrange[-1], xyrange[-1], xyrange[0]))
plt.imshow(data, extent'function: imshow')
plt.title(
222, projection='3d')
plt.subplot(= np.meshgrid(xyrange, xyrange)
X, Y ='viridis', edgecolor='none')
plt.gca().plot_surface(X, Y, data, cmap'function: plot_surface')
plt.title(
223)
plt.subplot(='viridis')
plt.contourf(X, Y, data, cmap'function: contourf')
plt.title(
224)
plt.subplot(40, cmap='viridis')
plt.contourf(X, Y, data, 'none') # Equivalent to 'linecolor','none' in MATLAB
plt.gca().set_facecolor('function: contourf (with more parameters)')
plt.title(
plt.tight_layout() plt.show()
<Figure size 640x480 with 0 Axes>
A bit more about images
# Load an image
= Image.open('../data/amsterdam.bmp')
amsterdam print(np.shape(amsterdam))
# Display the image
plt.figure()
plt.imshow(amsterdam)'image')
plt.axis('off')
plt.axis('viridis')
plt.set_cmap(
plt.show()
# Plot the individual color components
= 'RGB'
title_color_components for subploti in range(1, 5):
2, 2, subploti)
plt.subplot(if subploti < 4:
- 1])
plt.imshow(np.array(amsterdam)[:, :, subploti 'Plotting just the {} dimension.'.format(title_color_components[subploti - 1]))
plt.title(else:
plt.imshow(amsterdam)'Plotting all colors')
plt.title(
plt.tight_layout() plt.show()
(734, 700, 3)