Python matplotlib plotting series: 2D plot basics

Matplotlib is a python library for creating static, animated, and interactive plots. It is a powerful tool for publication-quality and interactive plots providing the users with various customized facilities. Because of its huge applications, it can be perplexing for the beginners who want to gain the very basics of matplotlib, especially those who want to get some quality plots for their work without diving into the long documentation of matplotlib. In this blog, basic 2D plotting in python via matplotlib pyplot library ( a library that provides MATLAB like interface) will be discussed.

Let, we want to plot this array as the x-axis: [1,4,7,...19]

And this array, its square, and cube will be plotted in the y axis.

First import pyplot:

import matplotlib.pyplot as plt

Then, create the necessary arrays:

x=[i for i in range(1,20,3)]
y1=[i for i in x]
y2=[i**2 for i in x ]
y3=[i**3 for i in x]

Single plot:

Lets plot the square values first:

plt.plot(x,y2,'rv-',linewidth=2,markersize=5)
plt.xlabel('x values',fontsize=12)
plt.ylabel('$x^2$ values',fontsize=12)
plt.xlim(1,20)
plt.ylim(1,)
fig = plt.gcf()
fig.set_size_inches(8,4.944)
fig.savefig('square graph.jpg',doi=600)



Now, let us discuss what is happening here:

plot() takes at least two arrays, the first is the array for x-axis and the second is for y-axis. If we don't add anything else, a plot will be produced with some default values of line width, style, marker, etc.

However, we can customize the style according to our requirements. For example:

  • We can change the line color. If we want to get a red line, we have to insert 'r-' where '-' indicates a line will be produced. Again if we want a red line with a downward triangle marker, we have to insert 'rv-'. Thus we can produce various colored lines with desired markers. The list of these symbols can be found here.
  • linewidth and markersize can be changed by assigning required values to them.
  • x axis label and y axis label can be defined via the xlabel() and ylabel() function. Note that we can change the font size of the label via fontsize calling. 
    Often we may need to put mathematical expression into the label. Python follows the rules of LATEX here. For example, in the given code, to write x square, we have to write it in a latex format like this - $x^2$.
  • The range of x-axis values and y-axis values can be defined via the xlim(lower value,upper value) and the ylim(lower value,upper value) functions.
  • gcf() gets the current figure .
  • We can set the dimensions of our graph manually via the set_size_inches() function. In this code, a golden ratio is maintained for professional looking.
  • We can save our plot in various formats. In this code, the plot is saved in jpg format, and the dpi is set to be 600.

Figure and axes (The object-oriented way to plot):

In Matplotlib, the figure (an instance of the class plt.Figure) can be thought of as a single container that contains all the objects representing axes, graphics, text, and labels. The axes (an instance of the class plt.Axes) is what we see above: a bounding box with ticks and labels, which will eventually contain the plot elements that make up our visualization.
We can do the same above example by figure and axis method as:
fig=plt.figure()
ax=plt.axes()
ax.plot(x,y2,'rv-',linewidth=2,markersize=5)
ax.set_xlabel('x values',fontsize=12)
ax.set_ylabel('$x^2$ values',fontsize=12)
ax.set_xlim(1,20)
ax.set_ylim(1,)
fig.set_size_inches(8,4.944)
fig.savefig('square graph.jpg',doi=600)

Notice that,while most plt functions translate directly to ax methods (such as plt.plot() → ax.plot(), plt.legend() → ax.legend(), etc.), this is not the case for all commands. In particular, functions to set limits, labels, and titles are slightly modified. For transitioning between MATLAB-style functions and object-oriented methods, make the following changes:
  • plt.xlabel() → ax.set_xlabel()
  • plt.ylabel() → ax.set_ylabel()
  • plt.xlim() → ax.set_xlim()
  • plt.ylim() → ax.set_ylim()
  • plt.title() → ax.set_title()
Also, notice that the figure is captured by plt.figure() instead of plt.gcf().
In the object-oriented interface to plotting, rather than calling these functions individually, it is often more convenient to use the ax.set() method to set all these properties at once. For example, the same example can be done as the following manner:
ax = plt.axes()
ax.plot(x,y2,'rv-',linewidth=2,markersize=5)
ax.set(xlim=(1, 20), ylim=(1,350),xlabel='x values', ylabel='$x^2$ values')
fig.set_size_inches(8,4.944)
fig.savefig('square graph.jpg',doi=600)

Subplot:

Axis method is pretty handy while plotting a subplt. Every plot can be configured easily. 

The following code generates a subplot of (2,2) array:

#creating a subplot
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y2)
axs[0, 0].set_title('simple plot')
axs[0, 1].plot(x, y2,linewidth=5)
axs[0, 1].set_title('changing thelinewidth to 5')
axs[1, 0].plot(x, y2,'r^', linewidth=3)
axs[1, 0].set_title('red line,triangle marker')
axs[1, 1].plot(x, y2,'go',markersize=6)
axs[1, 1].set_title('changing the markersize')

for ax in axs.flat:
    ax.set(xlabel='x values', ylabel='$x^2$ values')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
    ax.label_outer()


In this code, the previous example with various style has been implemented via a (2,2) subplot.

Multiple plot:

Finally,now lets plot all the three graphs in a single plot:

#Multiple plot in a single graph
plt.plot(x,y1,'go-',label='x values')
plt.plot(x,y2,'rv-',label='$x^2$ values')
plt.plot(x,y3,'b^-',label='$x^3$ values')
plt.xlabel('This is the x values',fontsize=12)
plt.ylabel('This is the y values',fontsize=12)
plt.legend(fontsize=10,loc='best')
fig = plt.gcf()
fig.set_size_inches(8,4.944)
plt.savefig('plot.jpg',dpi=600)
plt.show()


Notice that, a new function label is added here. It represents the title of the legend. Also, note that plt.legend() is added to show the legend bar. Finally, as it is a multiplot graph, we have to use plt.show() function to show all the three graphs in a single plot.

The full code is available here.

Comments