Data Visualization for absolute beginners[part 3/3]
Legends, labels, and titles
By now we have covered the basics of creating a figure canvas and add axes instances to it, Let’s now focus on how we can add titles, axis labels, and legends to our plots.
Figure titles
An axes contains the method set_title
which can be added to each axis instance in a figure.
ax.set_title("title");
Axis labels
Similarly, for setting xlabel and ylabel we use set_xlabel
and set_ylabel
respectively.
ax.set_xlabel("x")
ax.set_ylabel("y");
Legends
We will use label = “label text” keyword when plots are added to the figure, and then we are going to call legend() method without argument for adding it to the figure.
fig = plt.figure()ax = fig.add_axes([0,0,1,1])ax.plot(x, x**2, label="x**2")
ax.plot(x, x**3, label="x**3")
ax.legend()
Observe and see how the legend overlaps some of the actual plot!
We should note that the legend function takes the optional argument loc that is used to specify where the legend will be drawn.
See the documentation for more details
# We have a lot of optionsax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner# .. many more options are available# Most common to choose
ax.legend(loc=0) # let matplotlib decide the optimal location
fig
Setting colors, linewidths, linetypes
Matplotlib provides us a bunch of options for customizing colors, linewidths, and linetypes. These are used to change how our plot looks.
Colors with MatLab like syntax
Using matplotlib we will now define the color of lines in multiple ways. For eg ‘g — ’ means a green dashed line.
# MATLAB style line color and style
fig, ax = plt.subplots()
ax.plot(x, x**2, 'b.-') # blue line with dots
ax.plot(x, x**3, 'g--') # green dashed line
Colors with the color= parameter
Another way to define colors is by their RGB or HEX codes we can also provide alpha value to indicate the opacity.
fig, ax = plt.subplots()ax.plot(x, x+1, color="blue", alpha=0.5) # half-transparant
ax.plot(x, x+2, color="#8B008B") # RGB hex code
ax.plot(x, x+3, color="#FF8C00") # RGB hex code
Line and marker styles
Changing the line width can be done using linewidth
or lw
keyword. The line style can be selected using ls
orlinestyle
keyword. Linestyle defines the line type such as dashed line or a dotted line.
fig, ax = plt.subplots(figsize=(12,6))ax.plot(x, x+1, color="red", linewidth=0.25)
ax.plot(x, x+2, color="red", linewidth=0.50)
ax.plot(x, x+3, color="red", linewidth=1.00)
ax.plot(x, x+4, color="red", linewidth=2.00)# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="green", lw=3, linestyle='-')
ax.plot(x, x+6, color="green", lw=3, ls='-.')
ax.plot(x, x+7, color="green", lw=3, ls=':')# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="blue", lw=3, ls='-', marker='+')
ax.plot(x, x+10, color="blue", lw=3, ls='--', marker='o')
ax.plot(x, x+11, color="blue", lw=3, ls='-', marker='s')
ax.plot(x, x+12, color="blue", lw=3, ls='--', marker='1')# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8,markerfacecolor="yellow", markeredgewidth=3, markeredgecolor="green");
Control over axis appearance
Now we will be learning about controlling the axis sizing properties in a figure.
Plot range
To add ranges of the axes we can use set_ylim
and set_xlim
attributes to the axis object, or axis('tight')
for automatically getting "tightly fitted" axes ranges.
fig, axes = plt.subplots(1, 3, figsize=(12, 4))axes[0].plot(x, x**2, x, x**3)
axes[0].set_title("default axes ranges")axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range");
Special Plot Types
The matplotlib is not just restricted to these simple line plots, it also provides us many specialized plots that we can create such as bar plots, pie charts, scatter plots and much more.
But in my opinion it’s better to use seaborn for these special types of charts. And we will discuss about them in a different tutorial.
Before wrapping up let’s discuss a few more examples of these specialtype of plots.
Scatter Plot
plt.scatter(x,y)
Histogram
from random import sample
data = sample(range(1, 1000), 100)
plt.hist(data)
Rectangular Box Plot
data = [np.random.normal(0, std, 100) for std in range(1, 4)]# rectangular box plot
plt.boxplot(data,vert=True,patch_artist=True);
This wraps up the fundamental of this beautiful python library, and I hope you enjoyed learning it as much as I did while making this tutorial.
Congratulations! on completing part 3/3 of the series🎉🎉🎉
I will soon add more visualisation tutorials with slightly advanced libraries such as seaborn and plotly where we will be able to visualise more complex data.
Thanks for reading🙂
Further Readings
- http://www.matplotlib.org — The project web page for matplotlib.
- https://github.com/matplotlib/matplotlib — The source code for matplotlib.
- http://matplotlib.org/gallery.html — A large gallery showcaseing various types of plots matplotlib can create. Highly recommended!
- http://www.loria.fr/~rougier/teaching/matplotlib — A good matplotlib tutorial.
- http://scipy-lectures.github.io/matplotlib/matplotlib.html — Another good matplotlib reference