• Post author:
  • Post category:Pandas
  • Post last modified:May 17, 2024
  • Reading time:15 mins read
You are currently viewing How to Add Title to Pandas Plot?

In Pandas title arguments are used to add a title at the top of the plots. If a string is passed, print the string at the top of the figure. If a list is passed and subplots is True, print each item in the list above the corresponding subplot. In this article, I will explain how to add the title to the plots using title arguments.

Advertisements

Key Points –

  • Start by creating a plot using the plot() function provided by Pandas DataFrame. This function returns an AxesSubplot object representing the plot.
  • Assign the result of the plot() function to a variable (often named ax). This variable is an AxesSubplot object that allows you to modify various aspects of the plot.
  • Alternatively, you can set the title directly in the plot() function by providing the title as an argument when calling the function. This can be a more concise way to add a title.
  • After setting the title, display the plot using plt.show() to visualize the changes made. This step is crucial for rendering the plot with the added title.
  • Use the set_title() method on the AxesSubplot object to assign a title to the plot. Provide the desired title as an argument to this method.

1. Quick Example of Add Title to Pandas Plot

Below are quick examples of how to add title to pandas plot.


# Quick example of add title to pandas plot

# Example 1: create histogram with title
df.plot(kind = 'hist', title = 'Students Marks')

# Example 2: Create title of individual columns of histogram
 df.plot(kind='hist', subplots=True, title=['Maths', 'Physics', 'Chemistry'])

# Example 3: Get the individual column as a bar
df['death rate'].plot(kind="bar")

# Example 4: Set the labels and title
df['death rate'].plot(kind="bar", title="test")
plot.title("Death rate if corona virus")
plot.xlabel("Country")
plot.ylabel("Death Rate")

2. How to Add title to the Plots

The Python Pandas library is primarily focused on data analysis, but it also offers basic data visualization capabilities. While it is not solely a data visualization library, Pandas can create simple plots, which are useful for exploratory data analysis. The plot() function in Pandas is particularly practical for visualizing data, as it provides several different functions to create various types of plots from DataFrame variables. Using Pandas’ plot() function, we can efficiently plot multiple variables from a DataFrame.

To create a histogram using the default Pandas hist() method, we first need to create a Pandas DataFrame from a Python dictionary.


# Create DataFrame
import pandas as pd
import numpy as np
df = pd.DataFrame({
    'Maths': [80.4, 50.6, 70.4, 50.2, 80.9],
    'Physics': [70.4, 50.4, 60.4, 90.1, 90.1],
    'Chemistry': [40, 60.5, 70.8, 90.88, 40],
    'Students': ['Student1', 'Student1', 'Student1', 'Student2', 'Student2']
})
print(df)

Yields below output.


# Output:
  Maths  Physics  Chemistry  Students
0   80.4     70.4      40.00  Student1
1   50.6     50.4      60.50  Student1
2   70.4     60.4      70.80  Student1
3   50.2     90.1      90.88  Student2
4   80.9     90.1      40.00  Student2

In order to plot a histogram in Pandas, call the hist() function on a DataFrame. This will generate a histogram for each numeric column in the DataFrame.


# Create histogram with title
df.plot(kind = 'hist', title = 'Students Marks')
Pandas plot title
Histogram using pandas

3. Create Titles of Individual Columns

The following code demonstrates how to create individual titles for subplots in pandas. This program will create a histogram for each column in the DataFrame with individual titles for each subplot. Note that each subplot’s title is specified in the title parameter as a list corresponding to the columns in the DataFrame.


# Create title of individual columns of histogram
 df.plot(kind='hist', subplots=True, title=['Maths', 'Physics', 'Chemistry'])
Pandas plot title
Individual columns of a histogram

4. Create Sample Plot Bar with Labels

Pandas offers various methods to visualize data in the form of graphs. Among these, the Bar Plot is particularly significant and commonly used across applications and presentations. Bar charts can be quickly and easily created using data in Pandas DataFrames. They are highly effective for rapid data exploration and comparison of variable values between different groups. A bar chart can be drawn directly using matplotlib, it can be drawn for the DataFrame columns using the DataFrame class itself.

To create a bar graph using plot.bar(), we first need to create a Pandas DataFrame. Let’s create a DataFrame representing the worldwide death rate of COVID-19 during the pandemic. We’ll set a list of country names as the index, which will be displayed on the x-axis label, and the death rate as the measured value, displayed on the y-axis label.


# Create DataFrame
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"death rate":[316.3, 321.3, 117.2, 38.25, 302.2 ]}, index = ["USA", "Brazil", "Germany", "India", "Uk"])
print(df)

# Draw a plot bar chart
df.plot.bar()

Yields below output.


# Output:
         death rate
USA          316.30
Brazil       321.30
Germany      117.20
India         38.25
Uk           302.20
Pandas plot
Bar chart of DataFrame

Here’s the syntax to create a bar plot for individual columns of a given DataFrame. It is the same as Series are plotted in the same way.


# Get the individual column as a bar
df['death rate'].plot(kind="bar")

5. Set the Labels & Title

Adding labels to the x and y axes and setting a title in a bar graph can significantly enhance understanding. In Pandas plot(), you can achieve this using the Matplotlib syntax with the plt object imported from pyplot.

  • xlabel – It is utilized to specify the label of the x-axis.
  • ylabel – It is utilized to designate the label of the y-axis.
  • title – With this, you can set the title of the bars.

# Set the labels and title
df['death rate'].plot(kind="bar", title="test")
plt.title("Death rate of corona virus")
plt.xlabel("Country")
plt.ylabel("Death Rate")

Yields below output.

Pandas plot title

Frequently Asked Questions on Add Title to Pandas Plot

Can I add individual titles to subplots in a Pandas histogram?

You can add individual titles to subplots in a Pandas histogram. When using the plot() function with the subplots=True parameter, you can provide a list of titles using the title parameter.

How do I set axis labels for a Pandas plot?

To set axis labels for a Pandas plot, you can use the set_xlabel() and set_ylabel() methods on the AxesSubplot object. For example, ax.set_xlabel('X-axis Label') and ax.set_ylabel('Y-axis Label') will set the x and y-axis labels, respectively.

Is it possible to customize the layout of subplots in a Pandas plot?

It is possible to customize the layout of subplots in a Pandas plot. The layout parameter of the plot() function allows you to specify the number of rows and columns for the subplot layout.

Do I need to use plt.show() after adding a title to a Pandas plot?

After making modifications to the plot, including adding a title, you should use plt.show() to display the plot with the changes. This function is necessary to visualize the updated plot.

Conclusion

In this article, you have learned to add titles to plots using pandas here, I have added the title to the histogram plots and bar graphs using title keyword.

Happy learning !!

References