0

I am having some trouble trying to figure out how to title matplotlib subplots as part of a for loop, and am not sure how to use a referenced value as part of the title. I am using python.

I have the following dataframe:

Parameter   P1      P2     P3       P1      P2     P3      P1      P2     P3
Color       Blue    Red    Green    Blue    Red    Green   Blue    Red    Green
Size
--------------------------------------------------------------------------------
   Small    XX      XX     XX       XX      XX     XX      XX      XX     XX
  Medium    XX      XX     XX       XX      XX     XX      XX      XX     XX
     Big    XX      XX     XX       XX      XX     XX      XX      XX     XX

Then running the following code:

fig, axs = plt.subplots(nrows=1, 
                        ncols=5, 
                        figsize=(10, 3))

groups = df.groupby(level=1, axis=1)

for ax, group in zip(axs.flatten(), groups):
    group[1].plot(kind='bar', 
                  ax=ax,
                  color=['b', 'g', 'r'],
                  sharey=True,
                  legend=False,
                  rot=True)

I get three bar graphs, as I want. The only problem is that they are not titled. These 3 bar graphs are supposed to correspond to P1, P2, and P3. How can I title these subplots as part of the for loop so that they are titled "Parameter 1", "Parameter 2", and "Parameter 3"? I am very confused about how to enter a subplot title function in the for loop that references I prior order string.

The imports I used are:

from io import StringIO
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
  • `ax.set_title()` is how you would add it in basic Matplotlib. Pandas may also have a way to add a title directly in the `plot` call. – Jody Klymak Sep 24 '21 at 08:16
  • ... also please consider adding your imports and how you created `df`. I'm just assuming that is a pandas data frame, but... – Jody Klymak Sep 24 '21 at 08:17
  • yes it is a pandas dataframe. I just updated my post with the imports I used. – LostinSpatialAnalysis Sep 24 '21 at 08:29
  • ... and did you try `ax.set_title`? – Jody Klymak Sep 24 '21 at 08:33
  • Yes I tried `ax.set_title('Parameter_X')` in the first line of the for loop, indented right underneath: `for ax, group in zip(axs.flatten(), groups):`, but this gave the same "Parameter_X" title for each subplot. I want that "X" to be based on the Parameter number, whether P1, P2, or P3, but I am not sure how to access that within the groups. – LostinSpatialAnalysis Sep 24 '21 at 08:58
  • My ignorance of pandas is vast, however, google says: https://stackoverflow.com/questions/50859987/efficient-way-to-get-group-names-in-pandas – Jody Klymak Sep 24 '21 at 09:05
  • To `group[1].plot(...)`, add `title=group[0]` you must. See section **3.** of this [answer](https://stackoverflow.com/a/68793513/7758804). – Trenton McKinney Sep 25 '21 at 00:16

0 Answers0