shm2008
shm2008

Reputation: 1473

How to add title and xlabel and ylabel

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.

Upvotes: 44

Views: 188769

Answers (3)

gboffi
gboffi

Reputation: 25023

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

Upvotes: 9

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

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()

Upvotes: 79

Moran Neuhof
Moran Neuhof

Reputation: 446

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

Upvotes: 11

Related Questions