Introduction to MatPlotLib
Our previous article discusses a rudimentary introduction to MatPlotLib plotting. This included downloading, importing, saving and understanding the MatPlotLib interface. An understanding of these concepts is fundamental to executing all later functions, so if you haven’t thoroughly examined these topics, we highly recommend it. Resources can be found here. Presently, however, we move forward to elaborate on features of basic plotting. More precisely, we endeavor to thoroughly examine intricacies of basic plots in MatPlotLib. This will be an intermediate segway into more sophisticated and complex mechanisms of plotting. Nevertheless, the governing dynamics are well deserving of thorough accounting as well, and thus, we proceed.
Coding a Simple Line Plot
We will initiate our examination of basic MatPlotLib plots with simple line plots as a proxy. Basic line plots are defined by simple functions constituted by the form y=f(x). When we first commence construction of our plot, we import necessary libraries, including MatPlotLib and Numpy.
Firstly, we can begin by coding an empty figure plot with only axes present. We may do this with the plt.figure() and plt.axes() functions. This appears as follows:
Just this simple code produces the empty figure which appears as:
Constructing the Plot
For MatPlotLib plots, the figure can be thought of as a chest of objects that stores objects in the form of axes, texts, labels, and even the data. Fortunately, MatPlotLib affords its users the opportunity the ability to control a variety of these parameters. Let’s begin by populating our figure with some data. We may do this artificially by creating a Numpy array filled with input data and run this through a certain function, and store this as output. We can then graph these as ‘x’ and ‘y’ coordinates. Let’s execute this with the Numpy sine function.
If you recall from our previous article on MatPlotLib plotting, we might known that the interface we have employed here is MatPlotLib’s object-oriented interface. In this fashion, we create a figure object and apply axes to it and we directly populate the figure with data. We create the data here with the Numpy linspace function. If you have not had previous experience with Numpy, worry not; a series on Numpy will be published later. Nevertheless, the Numpy linspace function takes two bounds of numbers and the number of evenly spaced intervals between these bounds. Therefore, we are using 10,000 input points to construct this data. We then pass these inputs into the sine function using the np.sin function and specifying the input object. This code produces the following graph:
We can observe from this graph that MatPlotLib automatically sets the ‘x’ axis as determined by the limits of our input.
Populating Plots with Data
In addition to this, we can plot multiple functions on the same figure. We set a new (x,y) coordinate system to the same figure. Let us do this with the cosine function.
Here, specifying the ‘ax’ object, all we have done is added a new (x,y) coordinate system using the cosine function. Including this will plot both data sets on the same figure. It appears as follows:
Basic Plot Customization
MatPlotLib affords users the opportunity of plot customization to a rather high degree. One of the most useful customizations available is the user’s control over line color and design. In the image above from our plot of the sine and cosine function, we might note that the two lines are plotted in orange and blue color. However, when setting up the plot of these functions, we have a great deal of flexibility over what the line will look like. Firstly, we specify the form of the line, whether it’s solid, dashed, dotted, or alternating dashes and dots. All we have to do is specify the type in the plot function. Let us observe what this code might look like:
In terms of the degree of control we have over specifying line shape, we have several options. We may specify these types using the ‘linestyle’ keyword argument. We can specify solid, dashed, dashdot (alternating dots and dashes), or dotted lines. The graphs appear as follows:
Note that when these lines plot together, their colors are different even without having specified this feature. This is a default aspect of MatPlotLib, that colors alternate between lines for differentiation between data sets. Now, in addition to the keyword arguments specified earlier, we can also do so symbolically. This code appears as follows:
In addition to controlling line shape, we can directly control line color if we choose not to settle with MatPlotLib default of color alternation. The color keyword argument, specified when constructing the plot, permits this function. There are several methods by which to do this. You may list the word of the color itself, you can specify the first letter (with the rgbcmyk), with a float between the value of 0 and 1 for grayscale, and several others. Let us see how that plays our with code:
Let us take a moment to view the plot this code procures:
Finally, the linestyle and color keyword arguments can be used together in a non-keyword argument to specify both aspects at the same time. The code for applying this techique appears as follows:
This pseudo-symbolic code produces a plot of the following form:
Beyond the control over the manifestation of the data itself, MatPlotLib lends the ability to control of the plot’s structure. One aspect of this comes in the form of control over characterization of axes. Much of this comes from utilization of the xlim() and ylim() functions. Both of these functions take as inputs two arguments, the first being the minimum of the respective axis, and the second being the maximum of the respective axis. With our sine and cosine model, the code for exerting this control appears as follows:
For the x-axis, the minimum sets to -1 while the maximum sets to 25. On the other hand, the limits for the y-axis sets to -1 and 1.2 respectively. The plot that this code produces appears as:
Of additional import is an automatic function that may be passed into the axis function is the ‘tight’ argument. The ‘tight’ argument in a sense restricts the bounds of the plot to the extent of the function itself such that it uses the minimum amount of space. On the other hand, passing in the ‘equal’ argument makes the distance traversed in the x-dimension is equal to the distance traversed in the y-dimension. Let us examine the code that procures these differential effects:
Let us first take a look at the plot yielded by using the ‘tight’ argument:
Now, let us compare this to the plot yielded when using the ‘equal’ argument:
Addition of Plot Labels
When creating plots filled with data, it is imperative that we apply a variety of labels so that information is succinctly organized. The basic plot labels include titles, axes labels, and legends. The ‘plt.title’, ‘plt.xlabel’, and ‘plt.ylabel’ functions are the most efficient for controlling these specifications. Let’s take a look at how we can employ these functions in our code:
Using these functions produces a plot with the following labels:
Including a legend with the ‘plt.legend’ function without specifying any arguments will automatically create a legend. However, before we do this, we must give data labels to our sine and cosine functions. The code to do this appears as:
This code procures a plot which looks like:
The Take Away
MatPlotLib evidently possesses a variety of simple functions permitting a rather easy means for customizing the plots created therefrom. Beyond a relative ease of constructing the plots themselves, there are a host of customization features like colors and linestyles that allow for a more holistic control over the view of the plot. Furthermore, the use of labels provide for sophisticated organizing of data in a given plot. Hopefully this has given you a sufficient introduction into methodologies of MatPlotLib plot construction and customization. Thus, we can confidently state that a thorough introduction to basic plots in MatPlotLib has been given. If you desire to explore this subject further, consider checking out the MatPlotLib manual, found here. In the next article, we move on to discuss the intricacies of scatter plots.