First, I feel weird posting an answer against the co-lead developer of matplotlib. Obviously, @tacaswell knows matplotlib far better than I ever will. But at the same time, his answer wasn't dynamic enough for me. I needed a caption that would always be based on the position of the xlabel
, and couldn't just use text annotations.
I considered simply changing the xlabel
to add a newline and the caption text, but that wouldn't clearly differentiate the caption, and
you can't do things like change the text size or make it italic in the middle of a text string.
I solved this by using matplotlib's TeX capabilities. Here's my solution:
from matplotlib import pyplot as plt
from matplotlib import rc
import numpy as np
from pylab import *
rc['text', usetex=True]
file = open['distribution.txt', 'r']
txt="I need the caption to be present a little below X-axis"
x=[]
y=[]
for line in file:
new=line.rstrip[]
mystring=new.split["\t"]
x.append[mystring[0]]
y.append[mystring[1]]
fig = plt.figure[]
ax1 = fig.add_axes[[0.1,0.4,0.8,0.5]]
ax1.set_title["This is my title"]
ax1.set_xlabel[r'\begin{center}X-axis\\*\textit{\small{' + txt + r'}}\end{center}']
ax1.set_ylabel['Y-axis']
ax1.scatter[x,y, c='r']
plt.xlim[0, 1.05]
plt.ylim[0, 2.5]
plt.show[]
I did the same thing with the random scatter plot from tacaswell's answer, and here's my result:
One warning: if you tweak this to take input string variables, the strings may not be properly escaped for use with TeX. Escaping LaTeX code is already covered on Stack Overflow, at //stackoverflow.com/a/25875504/1404311 . I used that directly, and then could take arbitrary xlabels and captions.
To add caption below X-axis for a scatter plot, we can use text[] method for the current figure.
Steps
Create x and y data points using numpy.
Create a new figure or activate an existing figure using figure[] method.
Plot the scatter points with x and y data points.
To add caption to the figure, use text[] method.
Adjust the padding between and around the subplots.
To display the figure, use show[] method.
Example
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.random.rand[10] y = np.random.rand[10] fig = plt.figure[] plt.scatter[x, y, c=y] fig.text[.5, .0001, "Scatter Plot", ha='center'] plt.tight_layout[] plt.show[]
Output
Updated on 06-May-2021 13:00:19
- Related Questions & Answers
- Adding a line to a scatter plot using Python's Matplotlib
- Plot scatter points on polar axis in Matplotlib
- Plot scatter points using plot method in Matplotlib
- Adding a scatter of points to a boxplot using Matplotlib
- Adding extra axis ticks using Matplotlib
- Show the origin axis [x,y] in Matplotlib plot
- Moving X-axis in Matplotlib during real-time plot
- Plot a 3D surface from {x,y,z}-scatter data in Python Matplotlib
- Python Scatter Plot with Multiple Y values for each X
- How to make a discrete colorbar for a scatter plot in matplotlib?
- How to animate a scatter plot in Matplotlib?
- How to plot data against specific dates on the X-axis using Matplotlib?
- How to draw an average line for a scatter plot in MatPlotLib?
- Updating the X-axis values using Matplotlib animation
- Aligning table to X-axis using matplotlib Python
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.
Matplotlib.pyplot.title[]
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}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
import
matplotlib.pyplot as plt
y
=
[
0
,
1
,
2
,
3
,
4
,
5
]
x
=
[
0
,
5
,
10
,
15
,
20
,
25
]
plt.plot[x, y, color
=
'green'
]
plt.xlabel[
'x'
]
plt.ylabel[
'y'
]
plt.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
import
matplotlib.pyplot as plt
x
=
[
-
5
,
-
4
,
-
3
,
-
2
,
-
1
,
0
,
1
,
2
,
3
,
4
,
5
]
y
=
[]
for
i
in
range
[
len
[x]]:
y.append[
max
[
0
,x[i]]]
plt.plot[x, y, color
=
'green'
]
plt.xlabel[
'x'
]
plt.ylabel[
'y'
]
plt.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
import
matplotlib.pyplot as plt
import
numpy as np
language
=
[
'C'
,
'C++'
,
'Java'
,
'Python'
]
users
=
[
80
,
60
,
130
,
150
]
index
=
np.arange[
len
[language]]
plt.bar[index, users, color
=
'green'
]
plt.xlabel[
'Users'
]
plt.ylabel[
'Language'
]
plt.xticks[index, language]
plt.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
from
matplotlib
import
pyplot as plt
foodPreference
=
[
'Vegetarian'
,
'Non Vegetarian'
,
'Vegan'
,
'Eggitarian'
]
consumers
=
[
30
,
100
,
10
,
60
]
fig
=
plt.figure[]
ax
=
fig.add_axes[[
0
,
0
,
1
,
1
]]
ax.axis[
'equal'
]
ax.pie[consumers, labels
=
foodPreference,
autopct
=
'%1.2f%%'
]
plt.title[label
=
"Society Food Preference"
,
loc
=
"left"
,
fontstyle
=
'italic'
]
Output:
In the above data visualization of the pie chart, label
, fontweight
keyword 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
from
matplotlib
import
pyplot
import
numpy
signalTime
=
numpy.arange[
0
,
100
,
0.5
];
signalAmplitude
=
numpy.sin[signalTime]
pyplot.plot[signalTime, signalAmplitude, color
=
'green'
]
pyplot.xlabel[
'Time'
]
pyplot.ylabel[
'Amplitude'
]
pyplot.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
from
PIL
import
ImageTk, Image
from
matplotlib
import
pyplot as plt
testImage
=
Image.
open
[
'g4g.png'
]
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.