Search code examples
pythonmatplotlibtitleaxis-labels

Add a title or label to a single plot


I have a question about giving a plot a title and or labels. Most of the time i prefer to use a system like this:

import matplotlib.pyplot as plt 
x = [1,2,3,4]
y = [20, 21, 20.5, 20.8]

fig, axarr = plt.subplots(n,m)
axarr[n,m] = plt.plot(x,y)
axarr[n,m].set_xlabel('x label')
axarr[n,m].set_ylabel('y label')
axarr[n,m].set_xlabel('title')
etc

But for now i convert a matlab script and to be as close as possible i want to try a bit that system. I would expect that my code must look something like this:

import matplotlib.pyplot as plt 
x = [1,2,3,4]
y = [20, 21, 20.5, 20.8]

ax = plt.plot(x,y)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_xlabel('title')
etc

But now the labels/title give an error AttributeError: 'list' object has no attribute 'set_xlabel'

So i was looking around and find on https://sites.google.com/site/scigraphs/tutorial that the following code works out.

#import matplotlib libary
import matplotlib.pyplot as plt


#define some data
x = [1,2,3,4]
y = [20, 21, 20.5, 20.8]

#plot data
plt.plot(x, y, linestyle="dashed", marker="o", color="green")

#configure  X axes
plt.xlim(0.5,4.5)
plt.xticks([1,2,3,4])

#configure  Y axes
plt.ylim(19.8,21.2)
plt.yticks([20, 21, 20.5, 20.8])

#labels
plt.xlabel("this is X")
plt.ylabel("this is Y")

#title
plt.title("Simple plot")

#show plot
plt.show()

So basically is my question why can't i use the middle method for adding a label or title(please also why) but do i need or a subplot (method 1) or the method of the example?


Solution

  • As the documentation for plot() explains, plot() returns a list of Line2D objects, not an Axes, which is why your second code does not work.

    In essence, there are 2 ways to use matplotlib:

    • Either you use the pyplot API (import matplotlib.pyplot as plt). Then each command starts with plt.xxxxx() and they work on the last created Axes object, which you usually don't need to reference explicitly.

    Your code would then be:

    plt.plot(x,y)
    plt.xlabel('x label')
    plt.ylabel('y label')
    plt.xlabel('title')
    
    • Either you use the object-oriented approach

    where your code would be written:

    fig, ax = plt.subplots()
    line, = ax.plot(x,y)
    ax.set_xlabel('x label')
    ax.set_ylabel('y label')
    ax.set_xlabel('title')
    

    It is usually not recommended to mix both approaches. The pyplot API is useful for people migrating from MATLAB, but with several subplots, it gets difficult to be sure which Axes one's working on, therefore the OO approach is recommended.

    see this part of matplotlib FAQs for more information.