How to add Title to Subplots in Python?

share link

by aryaman@openweaver.com dot icon Updated: Jul 20, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Matplotlib is a popular Python library. It is used for creating static, animated, and interactive visualizations. It provides a versatile and powerful set of tools. These tools are used for generating various types of plots, charts, and graphs. Matplotlib is built on top of the NumPy library. It integrates well with other scientific computing libraries like SciPy and Pandas.  

 

The primary purpose of Matplotlib is to ease data visualization and exploration. It offers a wide range of plot types. It also includes line plots, scatter plots, bar plots, histograms, pie charts, and more. These plots can be customized to suit specific needs. It helps create publication-quality figures with precise control over various visual aspects.  

 

Matplotlib provides a flexible API. That allows users to create plots through a graphical user interface (GUI). It supports many output formats and interactive backends like Qt and Tkinter. This flexibility makes it suitable for a variety of applications. It will range from exploratory data analysis. It creates visualizations for reports, presentations, and web applications. Matplotlib is a popular data visualization library in Python. This library provides various plot types for analyzing and representing data.  

 

Different types of plots can be created with Matplotlib:  

  • Line Plot: A line plot is a basic plot type that displays data points connected by straight lines.  
  • Bar Plot: A bar plot (or bar chart) compares categorical data. Each category will represent this as a rectangular bar. This is done with the height proportional to the values it represents. Bar plots are used to show comparisons between different groups or categories.  
  • Histogram: A histogram is a plot that organizes numerical data into bins. This displays the frequency or count of values falling into each bin. It is useful for understanding the distribution and shape of a dataset.  
  • Scatter Plot: A scatter plot displays individual data points as markers. It will be displayed in a two-dimensional coordinate system. It is used to visualize the relationship between two continuous variables. It can identify any patterns, trends, or correlations between them.  
  • Pie Chart: A pie chart is a circular plot divided into slices. In it, each slice represents a category or proportion of a whole. Pie charts are useful for displaying a dataset's relative sizes or percentages.  
  • Area Plot: An area plot (or area chart) is like a line plot, but the area between the line and the x-axis is filled with color. It is useful for visualizing the cumulative values or proportions of many variables.  
  • Box Plot: A box plot is a compact visualization that displays the distribution of a dataset.  
  • Heatmap: It helps visualize large datasets' correlations, patterns, or densities. Heatmaps are particularly effective when working with matrices or two-dimensional arrays.  

 

Several parameters can be adjusted to customize its appearance while creating a plot. Here are some of the most common parameters:  

Title:  

The title of a plot provides a descriptive name or explanation of the data being visualized. The title can be customized with different font styles, sizes, and colors.  

Axis Labels:  

Axis labels provide information about the data represented on the x- and y-axes. They help understand the plotted data's scale, units, or meaning. In Matplotlib, the x-axis label can be set using plt.xlabel() and the y-axis label with plt.ylabel(). Like the title, axis labels can be formatted with different fonts, sizes, and colors.  

Tick Labels:  

These are the numeric or categorical values. That is displayed along the axes to say the position of data points. They help in interpreting the plotted data.  

Axis Limits:  

The limits of the x- and y-axes determine the range of values displayed in the plot. By default, Matplotlib adjusts the axis limits based on the plotted data. Yet, you can set the limits using plt.xlim() for the x-axis and plt.ylim() for the y-axis. This can be useful for zooming in on specific regions of the data. Also, it is used for maintaining consistent scales across many plots.  

Axis Scaling:  

Also, to the axis limits, you can adjust the axes' scaling. Matplotlib supports various scaling options, such as linear, logarithmic, symmetrical, and more. You can set the scaling using functions like plt.xscale() and plt.yscale().  

Gridlines:  

These are horizontal and vertical lines that run across the plot. This represents the major divisions on the axes. They aid in reading and interpreting the data points. Gridlines can be turned on or off using plt.grid(). It can be customized with different line styles and colors.  

Legend:  

If you have many data series or plot elements, a legend can be added to differentiate between them. The legend provides labels or descriptions for each element displayed in the plot. In Matplotlib, you can create a legend using plt.legend(). The legend can be positioned, styled, and formatted to match your requirements.  

 

To create a subplot in Matplotlib, you can use the subplot () function. This allows you to divide the figure into many smaller subplots. Each subplot can have its own data and plot type. Here's a step-by-step guide on how to create a subplot in Matplotlib:  

  • Import the necessary libraries.  
  • Create the main plot using the plot() function.  
  • Create the subplot using the subplot() function.  
  • Plot the data for the subplot using the desired plot type.  
  • Customize the main plot and subplot as needed.  


Here are some tips for customizing plots in matplotlib:  

  • Choosing Colors: You can use predefined named colors like 'red', 'blue', and 'green'.  
  • Setting Line Styles: You can customize the line style using the 'linestyle' parameter.  
  • Adding Markers: Markers can be used to highlight individual data points. You can specify the marker style using the 'marker' parameter.  
  • Changing Line Width: The line width is adjusted using the 'linewidth' parameter.  
  • Marker Size: We can adjust marker size using the 'markersize' parameter.  
  • Customizing Fonts: You can change the font properties such as size, weight, and family.  
  • Modifying Tick Labels: You can change the appearance of tick labels on the axes.  
  • Setting Figure Size: You can adjust the figure size to control the size and resolution of the plot.  
  • DPI: DPI (dots per inch) to control the size and resolution of the plot.  
  • Adding Legends: You can include legends to provide extra information about the plot.  
  • Annotations: you can include annotations to provide more information about the plot.  


When it comes to improving the appearance of plots created with Matplotlib. There are several techniques you can use to enhance the visual quality. Here are some tips to help you make your plots more pleasing:  

  • Adjusting the figure size and resolution.  
  • Choosing an appropriate style.  
  • Customizing colors and line styles.  
  • Adjusting axes limits and ticks.  
  • Adding labels and titles.  
  • Including a legend.  
  • Using grid lines.  
  • Applying custom fonts.  
  • Saving high-quality images.  


In conclusion, this essay has explored the powerful capabilities of Matplotlib. It is a versatile data visualization library in Python. We began by discussing the fundamental components of Matplotlib. It has figures, axes, and plots. This provides a flexible framework for creating a wide range of visualizations. We then delved into various types of plots. These types include line plots, scatter plots, bar plots, and histograms. These are used to showcase their applicability in different data analysis scenarios.  

Code

In this solution, we use the set_title function of the matplotlib library

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as d
import numpy as np
dataframe = pd.DataFrame( 
    columns = ['From Date',   'NO',          'NO2',       'NOx',    'CO',           'Ozone'],           
    data = [
        ['2018-12-30 00:00:00', 5.856666,    39.208341,   28.97,   331.280881,  19.778900],
        ['2018-12-30 01:00:00', 4.050059,    16.262145,   13.53,   454.031703,  25.075286],
        ['2018-12-30 02:00:00', 4.057806,    15.293990,   12.96,   466.502681,  24.825294],
        ['2018-12-30 03:00:00', 3.835476,    13.526193,   11.71,   446.526784,  25.033312],
        ['2018-12-30 04:00:00', 4.230690,    11.251531,   10.70,   355.638469,  25.748796],
        ['2020-01-01 05:00:00',    1,            2,        6.91,    4,             5],
['2020-01-01 06:00:00',            5,           10,        7.37,    13.2,          9],
['2020-01-01 07:00:00',            4,           13,        8.28,    4,             4],
['2020-01-01 08:00:00',            3,           9,         8.57,    3,             5],
['2020-01-01 09:00:00',            2,           4,         9.12,    4,             6]
    ]
)
dataframe['From Date'] = pd.to_datetime(dataframe['From Date'])
dataframe = dataframe.set_index('From Date')
dataframe.replace('NoData', np.nan, inplace= True)
dataframe['NOx']=dataframe['NOx'].astype(float)
dataframe['Month'] = dataframe.index.map(lambda x: x.strftime("%m"))
dataframe['Time'] = dataframe.index.map(lambda x: x.strftime("%H:%M"))
# Get the Unique Months
months = dataframe['Month'].unique()
# Creates subplots based on the number of months
fig, axes = plt.subplots(len(months),figsize=(10, 50))
fig.suptitle("fig.suptitle")  # <--------------

# Iterate over axes and months together
for month, ax in zip(months, axes):
    df = dataframe.loc[dataframe['Month'] == month]
    df = df.groupby('Time').describe()
    ax.plot(df.index, df['NOx']['mean'], linewidth=6.0, label=month)
    ax.plot(df.index, df['NOx']['75%'], color='g')
    ax.plot(df.index, df["NOx"]['25%'], color='r')
    ax.fill_between(df.index, df["NOx"]['mean'], df["NOx"]['75%'], alpha=.5, facecolor='g')
    ax.fill_between(df.index, df["NOx"]['mean'], df["NOx"]['25%'], alpha=.5, facecolor='r')
    ax.legend()
    ticks = ax.get_xticks()
    ax.set_xticks(np.linspace(ticks[0], d.date2num(
        d.num2date(ticks[-1]) + dt.timedelta(hours=3)), 5))
    ax.set_xticks(np.linspace(ticks[0], d.date2num(
        d.num2date(ticks[-1]) + dt.timedelta(hours=3)), 25), minor=True)
    ax.set_title("ax.set_title")  # <--------------
    ax.set_xlabel("ax.set_xlabel")  # <--------------
    ax.set_ylabel("ax.set_ylabel")  # <--------------
  1. Copy the code using the "Copy" button above, and paste it in a Python file in your IDE.
  2. Import pandas at the beginning of the code using this command: import pandas as pd
  3. Run the file and check the output.


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections

Dependent Libraries

numpyby numpy

Python doticonstar image 23755 doticonVersion:v1.25.0rc1doticon
License: Permissive (BSD-3-Clause)

The fundamental package for scientific computing with Python.

Support
    Quality
      Security
        License
          Reuse

            numpyby numpy

            Python doticon star image 23755 doticonVersion:v1.25.0rc1doticon License: Permissive (BSD-3-Clause)

            The fundamental package for scientific computing with Python.
            Support
              Quality
                Security
                  License
                    Reuse

                      matplotlibby matplotlib

                      Python doticonstar image 17559 doticonVersion:v3.7.1doticon
                      no licences License: No License (null)

                      matplotlib: plotting with Python

                      Support
                        Quality
                          Security
                            License
                              Reuse

                                matplotlibby matplotlib

                                Python doticon star image 17559 doticonVersion:v3.7.1doticonno licences License: No License

                                matplotlib: plotting with Python
                                Support
                                  Quality
                                    Security
                                      License
                                        Reuse

                                          Environment Tested 

                                          I tested this solution in the following versions. Be mindful of changes when working with other versions. 

                                          1. The solution is created in Python3.11. 

                                          Support

                                          1. For any support on kandi solution kits, please use the chat
                                          2. For further learning resources, visit the Open Weaver Community learning page.

                                          FAQ:  

                                          1. How can I add a title to a Matplotlib subplot?  

                                          To add a title to a Matplotlib subplot, you can use the set_title() method. Here's an example of how you can add a title to a subplot:  

                                           

                                          import matplotlib.pyplot as plt  

                                          # Create a figure and a subplot  

                                          fig, ax = plt.subplots()  

                                          # Plot your data or create your subplot  

                                          # Set the title for the subplot  

                                          ax.set_title("My Subplot Title")  

                                          # Display the plot  

                                          plt.show()  

                                           

                                          In the above example, fig, ax = plt.subplots() creates a figure and a single subplot. You can replace this line with your code if you have many subplots. It helps create the subplot, ax.set_title("My Subplot Title") sets the title for the subplot. You can replace "My Subplot Title" with your desired title. Finally, plt.show() displays the plot with the added title.  

                                           

                                          2. What is the best layout for many plots within a single figure?  

                                          The best layout can vary depending on the specific context and the number of plots to display. Here are a few common layout options to consider:  

                                          • Grid Layout: This is a popular choice when you have many plots.  
                                          • Vertical or Horizontal Stacking: If you have a few plots, you can stack them.  
                                          • Side-by-Side: For plots that are related or complementary to each other, you can place them.  
                                          • Nested Layout: In some cases, you may have plots that contain many subplots or panels.  
                                          • Custom Layout: Depending on the requirements of your data, you can create a custom layout.  


                                          3. How do I set the axis titles in Matplotlib subplots?  

                                          You can use the set_xlabel() and set_ylabel() methods on the Axes objects to set axis titles. Here's an example:  

                                           

                                          import matplotlib.pyplot as plt  

                                          # Create subplots  

                                          fig, ax = plt.subplots(2, 2)  

                                          # Set axis titles for each subplot  

                                          ax [0, 0].set_xlabel('X-axis')  

                                          ax [0, 0].set_ylabel('Y-axis')  

                                          ax [0, 1].set_xlabel('X-axis')  

                                          ax [0, 1].set_ylabel('Y-axis')  

                                          ax [1, 0].set_xlabel('X-axis')  

                                          ax [1, 0].set_ylabel('Y-axis')  

                                          ax [1, 1].set_xlabel('X-axis')  

                                          ax [1, 1].set_ylabel('Y-axis')  

                                          plt.show()  

                                           

                                          In this example, plt.subplots(2, 2) creates a 2x2 grid of subplots. The ax variable holds an array of Axes objects representing each subplot. By accessing each Axes object (ax [row, column]), you can call set_xlabel() and set_ylabel(). It sets the desired axis titles for that subplot. Finally, plt.show() is used to display the plot.  

                                           

                                          4. Can I customize the title text of my Matplotlib subplots?  

                                          Yes, you can customize the title text of your Matplotlib subplots. Matplotlib provides various methods and attributes to modify the title text.  

                                           

                                          5. Can I add a unified figure title across all my subplots?  

                                          Yes, adding a unified figure title across all your subplots is possible. Here's an example code snippet to achieve this:  

                                           

                                          import matplotlib.pyplot as plt  

                                          # Create subplots  

                                          fig, axs = plt.subplots(2, 2)  

                                          # Add titles to subplots  

                                          axs[0, 0].set_title('Subplot 1')  

                                          axs[0, 1].set_title('Subplot 2')  

                                          axs[1, 0].set_title('Subplot 3')  

                                          axs[1, 1].set_title('Subplot 4')  

                                          # Add a figure title  

                                          fig.subtitle('Unified Figure Title')  

                                          # Display the figure  

                                          plt.show()  

                                           

                                          In this example, fig.subtitle('Unified Figure Title') adds a title to the entire figure. The set_title() is used to set individual titles for each subplot. The suptitle() function sets the title above the subplots. 

                                          See similar Kits and Libraries