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.
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");
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 options
ax.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
Matplotlib provides us _a bunch _of options for customizing colors, linewidths, and linetypes. These are used to change how our plot looks.
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
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
#data-science #matplotlib #visualization #visual studio code