laythstag
laythstag

Reputation: 45

How do I add a title to a grouped pandas dataframe?

I am trying to change the title, the y axis title and the x axis numbers of histograms made from a grouped pandas dataframe. Here is an example of what I am talking about:

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from random import randint
plt.style.use('seaborn-whitegrid')

a = []
for i in range(200):
    a.append(randint(0, 1))
b = []
for i in range(200):
    b.append(randint(1, 3))

d = {'A': a, 'B': b}
df = pd.DataFrame(data=d)

df_group = df.groupby(['A'], as_index = True)

df_group.hist(bins=5)

This is what I see when I run the code: Original Plot

What I would like to do is to edit it in python to look like this (I made this in paint): Edited Plot

Any help would be appreciated.

Upvotes: 1

Views: 2343

Answers (1)

Gabriel A
Gabriel A

Reputation: 1827

This should get the result you want.

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from random import randint
plt.style.use('seaborn-whitegrid')

a = []
for i in range(200):
    a.append(randint(0, 1))
b = []
for i in range(200):
    b.append(randint(1, 3))

d = {'A': a, 'B': b}
df = pd.DataFrame(data=d)

df_group = df.groupby(['A'], as_index = True)

ax = df_group.hist(bins=5)
for i in range(len(ax)):
    ax[i][0][0].set_title(f"A-{i}")

I just iterated through the subplots and rename them manually.

Upvotes: 1

Related Questions