• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:17 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.

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

If you are in a hurry, below are some 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

In Python Pandas library is mainly focused for data analysis and it is not only a data visualization library but also using this we can create a basic plots. When we want to create exploratory data analysis plots, we can use Pandas is highly useful and practical. It provides several different functions to visualizing our data with the help of the plot() function. Use Pandas plot() function we can plot multiple variables of DataFrame.

Create a histogram using the pandas hist() method, which is a default method. For that, we need to create Pandas DataFrame using Python Dictionary. Let’s create DataFrame.


# Create DataFrame
import pandas as pd
import numpy as np
# Create DataFrame
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 using hist() function, DataFrame can call the hist(). It will return the histogram of each numeric column in the pandas DataFrame. For example,


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

3. Create Multiple Titles for Individual Subplots

The following code shows 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 provides different representations for showing the data in the form of graphs. One of the important diagrams is a Bar Plot and is rapidly used in many applications and presentations. We can make bar chart quickly and easily using data in Pandas DataFrames. Bar graph is one of the best for fast 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.

We can create a bar graph using a plot.bar() for, that we need to create Pandas DataFrame. Here I will create a single column DataFrame on world wide death rate of covid-19 in the pandemic. Here I have taken a list of country names as an index, it is set on an x-axis label and death rate as a measured value, is set on a y-axis label. For example,


# 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

We can use the below syntax and get the individual columns on a plot bar of a given DataFrame. It is the same as Series are plotted in the same way.

We can use the below syntax and get the individual columns on a plot bar 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 Axes Labeling & Set plot titles

If we give labeling of the x and y axis and set the title in a bar graph, it will give a better understanding to us. In Pandas plot(), labeling of the axis is done by using the Matplotlib syntax on the “plt” object imported from pyplot.

  • xlabel : It is used for set the label of x axis.
  • ylabel : It is used for set the label of y axis.
  • title : Using this we can set the title of 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
Pandas bar chart with xlabel, ylabel, and title, applied using Matplotlib pyplot interface.

Frequently Asked Questions on How to Add Title to Pandas Plot

How can I add a title to a Pandas plot?

To add a title to a Pandas plot, you can use the set_title() method on the AxesSubplot object returned by the plot() function. Alternatively, you can directly specify the title in the plot() function.

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, I have explained how to add title to plots using pandas here, I have added the title to the histogram plots and bar graphs using title keyword.

Happy learning !!

References

Vijetha

Vijetha is an experienced technical writer with a strong command of various programming languages. She has had the opportunity to work extensively with a diverse range of technologies, including Python, Pandas, NumPy, and R. Throughout her career, Vijetha has consistently exhibited a remarkable ability to comprehend intricate technical details and adeptly translate them into accessible and understandable materials. Follow me at Linkedin.