import matplotlib.pyplot as plt import numpy as np from IPython.display import HTML, Image from scipy.special import airy %matplotlib inline
Being able to plot high-quality, informative figures is one of the necessary tools for working in the sciences today. If your figures don't look good, then you don't look good. Good visuals not only help to convey scientific information, but also help to draw attention to your work. Often times good quality figures and plots play an important role in determining the overall scientific impact of your work. Therefore we will spend some time learning how to create high-quality, publication ready plots in Python using a Python module called Matplotlib.
Image(filename="images/mpl.png", width=700, embed=True)
Before generating plots in Python we must load the main Matplotlib module. We did so in the beginning of this notebook.
Plotting a simple function, such as a sine function, is easy to do. All we need are two arrays, one for the x values, and one for the f(x) values
x = np.linspace(-np.pi, np.pi) y = np.sin(x) plt.plot(x, y) plt.show()
Here, the plot command generates the figure, but it is not displayed until you run
show(). If we want, we can also also add some labels to the axes and a title to the plot. While we are at it, lets change the color of the line to red, and make it a dashed line.
x = np.linspace(-np.pi, np.pi) y = np.sin(x) plt.plot(x, y, "r--") # make line red 'r' and dashed '--' plt.xlabel("x") plt.ylabel("y") plt.title("sin(x)") plt.show()
Here the 'r' stands for red, but we could have used any of the built in colors:
We can also specify the color of a line using the color keyword argument
x = np.linspace(-np.pi, np.pi) y = np.sin(x) # Here a string from 0->1 specifies a gray value. plt.plot(x, y, "--", color="0.75") plt.show()
x = np.linspace(-np.pi, np.pi) y = np.sin(x) plt.plot(x, y, "-", color="#FD8808") # We can also use hex colors if we want. plt.show()