General tips and tricks
Data visualization is mainly about making your data easy to understand in a fast, interesting manner. It is therefore important to present your plots as clean, informative and proffesional as possible. We will now look at some small changes to your code that will help you achieve this.
- Use the fact that most settings in your figures and plots are changeable. The easiest and most important are such as xlabel(), ylabel() and title() that will help you describe your plot, while legend(), colors and linestyles will seperate different plots from eachother. More advanced changes may be making the axes log-scaled, or using markers to specify a certain area of the plot. In order to get better at this, look at other plots to see what they have done well, and what could have been done better. A great place to look for inspiration is the offical Matplotlib webpage, where a number of examples are already made.
Matplotlib supports using TeX when writing mathematical expressions. This makes math text very presentable while beeing easy to write. We recommend you to visit Matplotlib's "Writing mathematical expressions" to get a complete tutorial. Here is an example:
plt.title(r'$\phi = \frac{\zeta_{a} g}{\omega} e^{k z} cos(\omega t + k x)$')
produces .
When working with images, it is of great help to know the difference between different image formats, especially between PNG, JPG/JPEG and PDF. The following is only a short summary, but more detailed info may be found here.
- JPG images are ideal for posting photos and images online, as they keep file size down without much overall quality loss. They are also great for emailing preview images to clients, and for printing artwork and photographs at high resolution.
- PNG images are ideal for web graphics, especially logos, illustrations, and graphs. They can shrink to very small file sizes when colors and elements are limited, which is another plus. The greatest advantage of a PNG is that the image can be fully transparent, allowing you to place illustrations and designs atop backgrounds effortlessly. PNG is also a top choice if images will be edited and saved multiple times.
PDF images are ideal for printing, especially for graphic design, posters, and flyers. PDF images are also an ideal choice for storing images online when you intend them to be downloaded. PDFs keep your images in one packet so viewers can print and save designs and booklets easily.
Simple plot
Visit this page for full documentation on simple plots using pyplot.
More in-depth plot() documentation and legend() documentation.
Multiple figures and subplots
A very good and more detailed guide on subplots and figures can be found here.
import matplotlib.pyplot as plt import numpy as np # Some example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2)
A single plot
subplots() without arguments return a Figure and a single Axes. When dealing with multiple plots in the same figure, the different axes will seperate the different subplots from eachother within the figure.
Stacking subplots in one direction
The first two optional arguments of pyplot.subplots() define the number of rows and columns of the subplot grid.
When stacking in one direction only, the returned axs is a 1D numpy array containing the list of created Axes.
If you are creating just a few Axes, it's handy to unpack them immediately to dedicated variables for each Axes. That way, we can use ax1 instead of the more verbose axs[0].
To obtain side-by-side subplots, pass parameters 1, 2 for one row and two columns.
Stacking subplots in two directions
When stacking in two directions, the returned axs is a 2D numpy array. If you have to set parameters for each subplot it's handy to iterate over all subplots in a 2D grid using for ax in axs.flat:.
axes.flat is not a function, it's an atribute of the numpy.ndarray. ndarray.flat is a 1-D iterator over the array. This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of Python’s built-in iterator object.
Multiple figures with subplots
Creating multiple figures can be achieved in a number of ways. Below, we will demonstrate two different approaches.
To display all figures at once, only call plt.show() at the end of the last figure. As an extra practice, try moving the call or adding more, what happens, and why?
MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting commands apply to the current axes. You can create multiple figures by using multiple figure() calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:
A more detailed explanation of the subplot method used above is found in the code explaining Quiver autoscaling vs manually set axes.
Quiver plot
Quiver plots a 2D vector field of arrows.
More in-depth quiver documentation and functions.
The plot autoscaling does not take into account the arrows, so those on the boundaries may reach out of the picture. This is not an easy problem to solve in a perfectly general way. The recommended workaround is to manually set the Axes limits in such a case. An example showing autoscaling vs manually is shown below.
Contour plot
Further demos on contour plots and contour labels.
In the example below two types of contour plots are used, where contour and contourf draw contour lines and filled contours, respectively.
The call signature is contour([X, Y,] Z, [levels]), where X and Y are the coordinates of the values in Z, and Z is the height values over which the contour is drawn. Levels is optional, and determines the number and positions of the contour lines / regions.
3D Plots
3D Plotting is not used in most courses, but may be used as a great tool of learning, as the visual aspects of plotting often are even more reinforced in 3D plots. In this chapter, we want to show you how easy it is to set up a simple 3D plot using Matplotlib. Check out Matplotlib's tutorial on 3D Plots if you want to learn more about the possibilities in 3D.
3D Plots as a tool of learning may be especially useful when learning about linear wave theory in the course TMR4247 - Marine Technology - Hydrodynamics.
Plotting animation
Plots are often time-dependent, and even though most of them are easily interpeted by choosing a specific t0, making a small animation may help you get some extra insight to how the plot actually changes with time. We will now set up a simple animation using the 3D plot as an example. Because our main goal with this animation is to get a better understanding of how our function changes with time, we will not put to much effort into the aesthetics of our animaiton.
The animation below is slightly altered from the code above in order to make it a GIF.