Skip to content
Snippets Groups Projects
Commit 9487c026 authored by Thomas Bischof's avatar Thomas Bischof
Browse files

Merge branch 'master' into Cui_Tutorials

parents 47083084 81f1b5d4
Branches Cui_Tutorials
Tags
No related merge requests found
%% Cell type:markdown id: tags:
# Making figures and visualizing data
In this tutorial we cover some methods for opening, cleaning, analyzing, and plotting data. We will discuss:
* how to plot data
* the difference between vector and raster graphics
* how to adjust fonts and colors in your figure
* how to modify your figure to work on a black background
* Creating a surface plot
%% Cell type:code id: tags:
``` python
import os
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import numpy
import pandas
```
%% Cell type:markdown id: tags:
First, we load the data into memory for further work.
%% Cell type:code id: tags:
``` python
data_awake = pandas.read_csv(os.path.join("data", "awake_mouse.csv"))
data_asleep = pandas.read_csv(os.path.join("data", "asleep_mouse.csv"))
```
%% Cell type:markdown id: tags:
Take a look at the file to see what is inside:
%% Cell type:code id: tags:
``` python
#Print header of the file
print(list(data_awake.columns.values))
#Print shape
print(data_awake.shape)
#Look into the file
data_awake
```
%% Cell type:markdown id: tags:
Now create quick plot to see what the data look like.
%% Cell type:code id: tags:
``` python
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(data_awake["time/s"], data_awake["liver"])
ax.plot(data_awake["time/s"], data_awake["heart"])
ax.set_xlabel("Time (s)")
ax.set_ylabel("Counts")
ax.set_xlim((0, 4))
fig.tight_layout()
plt.show(fig)
```
%% Cell type:markdown id: tags:
Try making a copy of the code from the cell above this one, and modify the figure to:
* create a legend (ax.plot(..., label="...") and ax.legend())
* change the color of the plot (ax.plot(..., color="..."))
* change the labels on the axes (ax.set_xlabel)
* change the xticks to be integers (ax.set_xticks)
%% Cell type:code id: tags:
``` python
# * insert new plotting code here *
```
%% Cell type:markdown id: tags:
We can create subplots for each plot:
%% Cell type:code id: tags:
``` python
fig = plt.figure()
ax_liver = fig.add_subplot(2, 1, 1)
ax_heart = fig.add_subplot(2, 1, 2)
ax_liver.plot(data_awake["time/s"], data_awake["liver"])
ax_liver.set_title("Liver")
ax_heart.plot(data_awake["time/s"], data_awake["heart"])
ax_heart.set_title("Heart")
for ax in fig.axes:
ax.set_xlabel("Time (s)")
ax.set_ylabel("Counts")
ax.set_xlim((0, 4))
fig.tight_layout()
plt.show(fig)
```
%% Cell type:markdown id: tags:
We can also create subplots of various shapes and sizes using GridSpec: https://matplotlib.org/gallery/userdemo/demo_gridspec03.html#sphx-glr-gallery-userdemo-demo-gridspec03-py. Try rewriting the plot scripts here to use GridSpec
%% Cell type:code id: tags:
``` python
# write a version using GridSpec for the subplots
```
%% Cell type:markdown id: tags:
Saving to file is accomplished using the Figure.savefig method:
%% Cell type:code id: tags:
``` python
fig = plt.figure()
ax_liver = fig.add_subplot(2, 1, 1)
ax_heart = fig.add_subplot(2, 1, 2)
ax_liver.plot(data_awake["time/s"], data_awake["liver"])
ax_liver.set_title("Liver")
ax_heart.plot(data_awake["time/s"], data_awake["heart"])
ax_heart.set_title("Heart")
for ax in fig.axes:
ax.set_xlabel("Time (s)")
ax.set_ylabel("Counts")
ax.set_xlim((0, 4))
fig.tight_layout()
fig.savefig("time_data.pdf")
plt.show(fig)
```
%% Cell type:markdown id: tags:
Try changing the file type to png, eps, jpg, or other formats. For bitmapped files, add a keyword argument dpi=... and see the impact of changing the dpi.
%% Cell type:markdown id: tags:
We can also customize various aspects of sizes and fonts in the figure. For example, let's create a one-column figure targeted to an APS journal (https://journals.aps.org/prl/authors#tables-and-figures). We will also throw in a bunch of customization, look up the documentation online and see what it all means.
%% Cell type:code id: tags:
``` python
fig = plt.figure(figsize=(3.375, 3)) # 3 3/8 images is the width of a one-column figure
ax_liver = fig.add_subplot(2, 1, 1)
ax_heart = fig.add_subplot(2, 1, 2)
ax_liver.plot(data_awake["time/s"], data_awake["liver"])
ax_liver.set_ylabel("Liver", size="x-large")
ax_heart.plot(data_awake["time/s"], data_awake["heart"])
ax_heart.set_ylabel("Heart", size="x-large")
for ax in fig.axes:
ax.set_xlim((0, 4))
ax.set_yticks([])
ax.grid(True)
ax_liver.set_xticklabels([])
ax_heart.set_xlabel("Time (s)", size="large")
fig.tight_layout()
fig.subplots_adjust(hspace=0)
fig.savefig("time_data_aps.pdf")
plt.show(fig)
```
%% Cell type:markdown id: tags:
## Making your figure usable on a black background
A common aesthetic choice is the black background. This involves making new color choices for axes, text, and plotted data, as well as changing font styles and sizes to be more legible. Simply changing the background to black will not necessarily work well, as we will explore.
There are special style sheets which have been developed to be good for viewing on a black background. We will use these as a starting point.
* https://matplotlib.org/gallery/style_sheets/style_sheets_reference.html
* https://matplotlib.org/gallery/style_sheets/dark_background.html?highlight=dark%20background%20style%20sheet
* https://stackoverflow.com/questions/48391568/matplotlib-creating-plot-for-black-background-presentation-slides
* https://matplotlib.org/users/dflt_style_changes.html?highlight=style%20sheets
%% Cell type:code id: tags:
``` python
import numpy as np
import matplotlib.pyplot as plt
def plot_figure(style_sheet_label):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
ax.plot(x, np.sin(x + s), 'o-')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_title(style_sheet_label)
plt.show(fig)
for style_sheet_label in ["dark_background", "default", "grayscale", 'seaborn-colorblind']:
with plt.style.context(style_sheet_label):
plot_figure(style_sheet_label)
```
%% Cell type:markdown id: tags:
Use the space below to make a custom figure with a black background. Try using the figure on a projector or television: is it legible from a distance? If not, make changes until you are satisfied.
%% Cell type:code id: tags:
``` python
# insert new plotting routine here
```
%% Cell type:markdown id: tags:
## Advanced ideas in colormaps
In addition to aesthetics, the choice of a colormap can dramatically influence your interpretation of the data which are displayed. Below are some links to discussions of these effects in the context of scientific data:
* [Perceptual uniformity and the importance of default colormaps](http://bids.github.io/colormap/)
* [Impact of color and transparency when interpreting overlaid data](https://www.osapublishing.org/boe/abstract.cfm?uri=boe-6-10-3765)
* [Diverging color maps for scientific visualization](https://www.kennethmoreland.com/color-maps/ColorMapsExpanded.pdf)
* [A Better Default Colormap for Matplotlib](https://www.youtube.com/watch?v=xAoljeRJ3lU)
* [A New Colormap for Matlab](https://blogs.mathworks.com/steve/2014/10/20/a-new-colormap-for-matlab-part-2-troubles-with-rainbows/)
* [Are there good reasons to avoid using color in research papers?](https://academia.stackexchange.com/questions/13616/are-there-good-reasons-to-avoid-using-color-in-research-papers)
### Colormaps for the color-blind
There are additional factors that you may want to consider for accessibility to the colorblind. See the following links for discussion and suggestions:
* [How to make figures and presentations that are friendly to Colorblind people](https://jfly.uni-koeln.de/color/index.html)
* [Viewing Color-blind Previews in Adobe Illustrator](https://indesignsecrets.com/viewing-color-blind-previews-of-pages.php)
%% Cell type:markdown id: tags:
## Creating a surface plot
%% Cell type:code id: tags:
``` python
#Formula for some shape
def f(x,y):
return(numpy.sin(x**2 + y**2) + numpy.cos(x**2 + y**2))
x = numpy.linspace(-10, 10, 40)
y = numpy.linspace(-10, 10, 40)
#Make coordinate arrays
X, Y = numpy.meshgrid(x, y)
Z = f(X, Y)
```
%% Cell type:code id: tags:
``` python
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='plasma')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
#Change view (evaluation 60° and azimuth 35°)
ax.view_init(60, 35)
fig.tight_layout()
plt.show(fig)
```
%% Cell type:markdown id: tags:
Try customing the plot for this function:
* Create a 2D contour plot instead of a 3D surface plot
* How do you manipulate the levels? Can you customise them for you? Create a plot with only three contour levels with three custom colours.
* Add a color bar showing the meaning of the colors
* Change the background to be transparent, rather than grey
* Instead of plotting our current surface, plot a sphere
%% Cell type:code id: tags:
``` python
# insert new figures here
```
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment