This page aims to explain how to add a title to your python chart, and how to customise it. This is done through the title function of Matplotlib.
-
With Matplotlib, the title is added using the … title function!
# libraries import matplotlib.pyplot as plt import numpy as np # An histogram 2D x = np.random.normal(size=50000) y = x * 3 + np.random.normal(size=50000) plt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.Reds) # Add a basic title plt.title("A 2D histogram")
-
- #190 Title position
- #190 Title position
It is possible to modify the position of your title through the ‘loc‘ argument. Three main possibilities exist: left, center, and right. Once this is chosen, you can adjust the position more precisely with the horizontalalignment and verticalalignment arguments.
# Control position. Available = ‘center’, ‘left’, ‘right’ plt.title("A 2D histogram", loc='left') # Then you can adjust with horizontalalignment ('center', 'right', 'left') and # verticalalignment ('top', 'bottom', 'center', 'baseline') plt.title("A 2D histogram", loc='left', horizontalalignment='center', verticalalignment='center')
-
You can control the font of the title. Here I added a first title on the left, big, italic and purple. The second title is written in bold. To write in bold you need to use the same method than for mathematic equation.
# Italic and purple, size 20 plt.title("A 2D histogram", fontsize=20, fontweight=0, color='purple', loc='left', style='italic' ) # to write in bold plt.title( "$\mathbf{write in bold}$" , loc="right")
-
It is quite easy to display your title on several lines. Just put ‘\n‘ wherever you want to skip to next line. However, you will probably have to deal with margins if you want to export your image.
plt.title('A 2D histogram\nwith the Reds palette', loc='left') # Use plt.subplots_adjust(top=0.7) if you need to save your image. It avoids title to be truncated.
-
You can add several titles. Just call the title function several times.
# Fist title plt.title("A 2D histogram", loc='left', fontsize=18) # Second title plt.title("made in Python", loc='right', fontsize=13, color='grey', style='italic')
-
You can insert Mathematical equations and symbols. Here is a basic example. Note that the Matplotlib documentation is really complete concerning this matter.
plt.title("$\mathcal{A}\mathrm{sin}(2 \omega t)$", fontsize=22)
-
You can add a suptitle. In this case, note the importance to use the y argument to control the space between title and suptitle.
plt.suptitle("A 2D histogram\n", fontsize=18, y=1.02) plt.title("Realized by the Python Graph Gallery", color="grey", style='italic')
-
You can control the space dedicated to the title on your plot. Just increase or decrease the top margin as follows:
plt.title("A 2D histogram", y=1.05)