Reputation: 186
I want to add title for each subplot. I want to assign a separate title to each subplot from a list of title in same sequence.
title_list = ['Table1', 'Table2',, 'Table3', 'Table4', 'Table5, 'Table6']
Hence assign title for df1 as 'Table1', df2 as 'Table2'.. and so on.
My Code as below:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
df_list[count].plot(ax=axes[r,c])
count+=1
Upvotes: 1
Views: 2553
Reputation: 571
Add ax.set_title
like below
for r in range(nrow):
for c in range(ncol):
axes[r,c].set_title(title_list[(r*c) + c])
df_list[count].plot(ax=axes[r,c])
count+=1
Upvotes: 1
Reputation: 9093
You can use the method set_title()
on the axis object:
axes[r, c].set_title(f"This is row={r} and column={c}")
I also added a call fig.tight_layout()
to fix the spacing between subplots.
The complete code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
df_list[count].plot(ax=axes[r,c])
count+=1
axes[r, c].set_title(f"This is row={r} and column={c}")
fig.tight_layout()
Note that you can simplify the creation of your sample data:
# dataframe sample data
df_list = [pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
for _ in range(nrow * ncol)]
Upvotes: 2