<jupyter_start><jupyter_text>This notebook uses the plots from the following paper to explain Matplotlib is <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, "High-dimensional geometry of population responses in visual cortex", Nature, 2018.The official repository for the code related to this paper is here: https://github.com/MouseLand/stringer-pachitariu-et-al-2018bData for this notebook can be downloaded from https://figshare.com/articles/dataset/Recordings_of_ten_thousand_neurons_in_visual_cortex_in_response_to_2_800_natural_images/6845348 We rely on the following matplotlib book for material https://matplotlib.org/2.0.2/Matplotlib.pdf  Importing necessary libraries<jupyter_code>import matplotlib.pyplot as plt
import scipy.io as sio
import numpy as np
from scipy.stats import zscore

from matplotlib.ticker import NullFormatter<jupyter_output><empty_output><jupyter_text>Opening .mat data in Python and first plot We load a \*.mat file containing data into a numpy array and make a fist plot.<jupyter_code>import scipy.io as sio
mt = sio.loadmat('natimg2800_M160825_MP027_2016-12-14.mat')

### stimulus responses
resp = mt['stim'][0]['resp'][0]    # stimuli by neurons
istim = mt['stim'][0]['istim'][0]   # identities of stimuli in resp
spont = mt['stim'][0]['spont'][0]  # timepoints by neurons<jupyter_output><empty_output><jupyter_text>It is useful to plot shapes of the loaded numpy arrays using .shape<jupyter_code>print('Shape of neural response array: {}'.format(resp.shape))
print('Shape of stimulus identity response array: {}'.format(istim.shape))
print('Shape of spontaneous activity array: {}'.format(spont.shape))<jupyter_output>Shape of neural response array: (5426, 11449)
Shape of stimulus identity response array: (5426, 1)
Shape of spontaneous activity array: (4696, 11449)<jupyter_text>Plot the response of one neuron for 500 first timepoints.<jupyter_code>plt.plot(resp[:500,0])<jupyter_output><empty_output><jupyter_text>Load stimuli as images using plt.imshow.<jupyter_code>### loading images
mt = sio.loadmat('images_natimg2800_all.mat')
imgs = mt['imgs']  # 68 by 270 by number of images
# check out first image using matplotlib.pyplot
plt.imshow(imgs[:,:,0])<jupyter_output><empty_output><jupyter_text>Chapter 3.1 from Matplotlib book-- Introduction The Matplotlib book can be found here https://matplotlib.org/2.0.2/Matplotlib.pdf<jupyter_code>#z-score the data to have mean 0 and standard deviation 1
zsc=zscore(resp,axis=1)
plt.plot(zsc[:,0],zsc[:,1],'ro',alpha=0.5)<jupyter_output><empty_output><jupyter_text>Let's transform the raw data!<jupyter_code>x=zsc[:,0]
y=zsc[:,1]
#plot with various axes scales
plt.figure(1)
# linear
plt.subplot(221)
plt.plot(x, y,'bo',alpha=0.3,markersize=1.5)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)

plt.subplot(222)
plt.plot(x,y,'ro',alpha=0.3,markersize=1.5)
plt.yscale('log')
plt.title('log')
plt.grid(True)

# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean(),'go',alpha=0.3,markersize=1.5)
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

plt.subplot(224)
plt.plot(x, y,marker='o',c='indianred',alpha=0.3,markersize=1.5)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())

plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.35,
wspace=0.35)
plt.show()<jupyter_output><empty_output><jupyter_text>Plot of zscored neural activities.<jupyter_code>t=range(0,100)
offset=[0,5,10]
plt.plot(t, zsc[:100,0]+offset[0], 'r--',t,zsc[:100,15]+offset[1],'bs',t,zsc[:100,10]+offset[2], 'g^')
plt.yticks([])
plt.show()<jupyter_output><empty_output><jupyter_text>But the ticks are confusingly large! Can we make them smaller?<jupyter_code>t=range(0,100)
offset=[0,5,10]
plt.plot(t, zsc[:100,0]+offset[0], 'r--',markersize=5)
plt.plot(t,zsc[:100,15]+offset[1],'bs',markersize=3)
plt.plot(t,zsc[:100,10]+offset[2], 'g^',markersize=2)
plt.yticks([])
plt.show()<jupyter_output><empty_output><jupyter_text>Let's annotate an outlier.<jupyter_code>t=range(0,100)
plt.plot(t,zsc[:100,10], 'g^',markersize=2)
plt.annotate('outlier', xy=(8, 7), xytext=(10, 9), arrowprops=dict(facecolor='black', shrink=0.05),)
plt.ylim(-1,10)
plt.show()<jupyter_output><empty_output><jupyter_text>You can add text (including latex formulas) and labels to the plot.<jupyter_code># the histogram of the data
mean=np.mean(resp[:,0])
std=np.std(resp[:,0])
print(mean)
print(std)
n, bins, patches = plt.hist(resp[:,0], 50,  facecolor='g', alpha=0.75)
plt.xlabel('Neural activity')
plt.ylabel('Probability')
plt.xlim(0,200)
plt.axvline(18.52,c='black')
plt.title('Distribution of activation values in an example neuron')
plt.text(25, 1500, r'$\mu=18.52,\ \sigma=34.46$')<jupyter_output>18.52377
34.469643<jupyter_text>We can also use plt.plot() to draw a line and control it's width!<jupyter_code>t=range(0,100)
plt.plot(t, zsc[:100,99], linewidth=2.0)<jupyter_output><empty_output><jupyter_text>You can also set multiple properties using the .setp() function on the line object.<jupyter_code>line,=plt.plot(t,zsc[:100,150])
plt.setp(line,color='r')<jupyter_output><empty_output><jupyter_text>To get a list of settable line properties, call the setp() function with a line or lines as argument<jupyter_code>plt.setp(line)<jupyter_output>agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
  alpha: float
  animated: bool
  antialiased or aa: bool
  clip_box: `.Bbox`
  clip_on: bool
  clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
  color or c: color
  contains: callable
  dash_capstyle: {'butt', 'round', 'projecting'}
  dash_joinstyle: {'miter', 'round', 'bevel'}
  dashes: sequence of floats (on/off ink in points) or (None, None)
  drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
  figure: `.Figure`
  fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
  gid: str
  in_layout: bool
  label: object
  linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  linewidth or lw: float
  marker: marker style
  markeredgecolor or mec: color
  markeredgewidth or mew: float
  markerfacecolor or mfc: color
  markerfacecoloralt or mfcalt: color
  markersize or ms: float
  m[...]<jupyter_text>Exercise: Play around with the setp properties according to the list given above to set various properties of the plot! We can treat the response matrix over multiple cells as an image and use powerful matplotlib functions to plot this image<jupyter_code>imgplot=plt.imshow(resp[:2000,:1000].T)<jupyter_output><empty_output><jupyter_text>You can change the cmap of the image.<jupyter_code>imgplot=plt.imshow(resp[:2000,:1000].T)
imgplot.set_cmap('nipy_spectral')<jupyter_output><empty_output><jupyter_text>You can interpolate the image.<jupyter_code>imgplot=plt.imshow(resp[:1000,:500].T,interpolation='bicubic')
imgplot.set_cmap('nipy_spectral')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15195389373067192, 'fraction_numerical': 0.04413831880798426, 'mean_word_length': 6.8792912513842746, 'pattern_counts': {'":': 0, '<': 71, '<?xml version=': 0, '>': 71, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '364011', 'license': 'MIT', 'n_tokens_mistral': 2883, 'n_tokens_neox': 2633, 'n_words': 617, 'path': 'StringerEtAl2018.ipynb', 'repo_name': 'mariakesa/MatplotlibForNeuroscientists', 'size': '7167'}