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. Also, check out our page Tips and tricks for coding.
Figure and plot appearance
Use the fact that the appearance of 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.
Mathematical text
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 .
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 Plot
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.
Keep in mind that this is not the best approach when making good, smooth animations, but rather a fast and easy setup.
The animation below is slightly altered from the code above in order to make it a GIF.
If you want to learn about the more advanced, preffered methods of animation in Matplotlib, matplotlib.animation is a good place to start. A basic example is shown below.
Exercises and solutions
If you want have a look at some exercises and solutions regarding NumPy, Matplotlib and data visualization, visit Exercises and solutions, data visualization in Python.
The exercises provided will have a varying degree of difficulty, thus including more advanced and detailed methods than described here.
Other recommended tutorials on data visualization
- Department of Statistics at the University of California, Berkeley, has made great tutorial on plotting using Matplotlib. This is really worth checking out: link.