Matplotlib.pyplot.title() in Python - GeeksforGeeks

05 Jan, 2022
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The title() method in matplotlib module is used to specify title of the visualization depicted and displays the title using various attributes.
Syntax: matplotlib.pyplot.title(label, fontdict=None, loc=’center’, pad=None, **kwargs)
Parameters:
label(str): This argument refers to the actual title text string of the visualization depicted.
fontdict(dict) : This argument controls the appearance of the text such as text size, text alignment etc. using a dictionary. Below is the default fontdict:fontdict = {‘fontsize’: rcParams[‘axes.titlesize’],‘fontweight’ : rcParams[‘axes.titleweight’],‘verticalalignment’: ‘baseline’,‘horizontalalignment’: loc}
fontdict = {‘fontsize’: rcParams[‘axes.titlesize’],‘fontweight’ : rcParams[‘axes.titleweight’],‘verticalalignment’: ‘baseline’,‘horizontalalignment’: loc}
loc(str): This argument refers to the location of the title, takes string values like 'center', 'left' and 'right'.
pad(float): This argument refers to the offset of the title from the top of the axes, in points. Its default values in None.
**kwargs: This argument refers to the use of other keyword arguments as text properties such as color, fonstyle, linespacing, backgroundcolor, rotation etc.
Return Type: The title() method returns a string that represents the title text itself.
Below are some examples to illustrate the use of title() method:
Example 1: Using matplotlib.pyplot to depict a linear graph and display its title using matplotlib.pyplot.title().
Python3
# importing module import matplotlib.pyplot as plt     # assigning x and y coordinates y = [0,1,2,3,4,5]x= [0,5,10,15,20,25]  # depicting the visualizationplt.plot(x, y, color='green') plt.xlabel('x') plt.ylabel('y')   # displaying the titleplt.title("Linear graph")  plt.show() 
Output:
In the above example, only the label argument is assigned as “Linear graph” in the title() method and the other parameters are assigned to their default values. Assignment of the label argument is the minimum requirement to display the title of a visualization.
Example 2: Using matplotlib.pyplot to depict a ReLU function graph and display its title using matplotlib.pyplot.title().
Python3
# importing module import matplotlib.pyplot as plt     # assigning x and y coordinatesx = [-5,-4,-3,-2,-1,0,1,2, 3, 4, 5]y = []  for i in range(len(x)):    y.append(max(0,x[i]))  # depicting the visualizationplt.plot(x, y, color='green') plt.xlabel('x') plt.ylabel('y')   # displaying the titleplt.title(label="ReLU function graph",          fontsize=40,          color="green")
Output:
The above program illustrates the use of label argument, fontsize key of the fontdict argument and color argument which is an extra parameter(due to **kwargs) which changes the color of the text.
Example 3: Using matplotlib.pyplot to depict a bar graph and display its title using matplotlib.pyplot.title().
Python3
# importing modules import matplotlib.pyplot as pltimport numpy as np  # assigning x and y coordinateslanguage = ['C','C++','Java','Python']users = [80,60,130,150]  # depicting the visualizationindex = np.arange(len(language))plt.bar(index, users, color='green')plt.xlabel('Users')plt.ylabel('Language')plt.xticks(index, language)  # displaying the titleplt.title(label='Number of Users of a particular Language',           fontweight=10,           pad='2.0')
Output:
Here, the fontweight key of the fontdict argument and pad argument is used in the title() method along with the label parameter.
Example 4: Using matplotlib.pyplot to depict a pie chart and display its title using matplotlib.pyplot.title().
Python3
# importing modules from matplotlib import pyplot as plt  # assigning x and y coordinatesfoodPreference = ['Vegetarian', 'Non Vegetarian',                   'Vegan', 'Eggitarian']  consumers = [30,100,10,60]  # depicting the visualizationfig = plt.figure()ax = fig.add_axes([0,0,1,1])ax.axis('equal')ax.pie(consumers, labels = foodPreference,        autopct='%1.2f%%')  # displaying the titleplt.title(label="Society Food Preference",          loc="left",          fontstyle='italic')
Output:
In the above data visualization of the pie chart, label, fontweightkeyword from fontdict and fontstyle(**kwargs) argument(takes string values such as 'italic', 'bold' and 'oblique') is used in the title() method to display the title of the pie chart.
Example 5: Using matplotlib.pyplot to visualize a signal in a graph and display its title using matplotlib.pyplot.title().
Python3
# importing modules from matplotlib import pyplot  import numpy      # assigning time values of the signal # initial time period, final time period# and phase angle  signalTime = numpy.arange(0, 100, 0.5);     # getting the amplitude of the signal signalAmplitude = numpy.sin(signalTime)     # depicting the visualization pyplot.plot(signalTime, signalAmplitude, color ='green')   pyplot.xlabel('Time') pyplot.ylabel('Amplitude')   # displaying the titlepyplot.title("Signal",             loc='right',             rotation=45)
Output:
Here, the label argument is assigned to 'signal' , loc argument is assigned to 'right' and the rotation argument (**kwargs) which takes angle value in degree is assigned to 45 degrees.
Example 6: Using matplotlib.pyplot to show an image and display its title using matplotlib.pyplot.title().
Python3
# importing modules from PIL import ImageTk, Image  from matplotlib import pyplot as plt  # depicting the visualizationtestImage = Image.open('g4g.png')  # displaying the title plt.title("Geeks 4 Geeks",          fontsize='20',          backgroundcolor='green',          color='white')plt.imshow(testImage)
Output:
In the above example, the title of an image is displayed using the title() method having arguments label as "Geeks 4 Geeks", fontsize key from fontdict as '20', backgroundcolor and color are extra parameters having string values 'green' and 'white' respectively.
kashishsoda
Matplotlib Pyplot-class
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java