How to add title and xlabel and ylabel

Question:

Is there a way to add title (and xlabel and ylabel) to plt.scatter(x,y,…) or plt.plot(x,y,…) directly without writing additional lines?

It is easy to add it when we use Series_name.plot in which we simply write Series_name.plot(…,title=’name’) but it does not work for me if I write: plt.scatter(…,title=’name’) or plt.plot(…,title=’name’)

[plt<< import matplotlib.pyplot as plt]

I am using Python 3.

Asked By: shm2008

||

Answers:

It’s as simple as adding:

plt.xlabel('your xlabel')
plt.ylabel('your ylabel')
plt.title('your title')

after the plt.scatter() command.
Then, write plt.show() to display the image with the labels and titles.
You may read about it more here: http://matplotlib.org/users/text_intro.html

Answered By: Moran Neuhof

From the documentation of plt.scatter() there is no such arguments to set the title or labels.

But neither does the plt.plot() command have such arguments. plt.plot(x,y, title="title") throws an error AttributeError: Unknown property title. So I wonder why this should work in either case.

In any case, the usual way to set the title is plt.title. The usual way to set the labels is plt.xlabeland plt.ylabel.

import matplotlib.pyplot as plt

x= [8,3,5]; y = [3,4,5]
plt.scatter(x,y)
plt.title("title")
plt.xlabel("x-label")
plt.ylabel("y-label")
plt.show()

You cannot add title, xlabel, ylabel etc w/o additional lines but you can use a single additional line if you think this is better

import matplotlib.pyplot as plt
plt.scatter([1,2,3,4,5,6],[3,5,3,2,4,7])
plt.gca().update(dict(title='SCATTER', xlabel='x', ylabel='y', ylim=(0,10)))

This approach has more sense if you want to apply the same attributes to a bunch of plots, because you can prepare in advance a dictionary to set all the parameters that you want to apply to each plot.

enter image description here

Answered By: gboffi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.