How to give different titles to matplotlib plots when parsing from csv?

Viewed 136

I wrote the python code below to read a CSV and generate multiple plots at once. However, I can't figure out how to give matplotlib the Location value from the csv I'm reading as I would like to have each plot labeled with the location value that I am aggregating on. Please see the code and screenshot below.

import pandas as pd
import datetime
import csv
import matplotlib.pyplot as plt
from google.colab import files
import matplotlib.pyplot as plt
import numpy as np

myfile = files.upload()
df = pd.read_csv('Electricity.csv')
df2 = df.groupby(['Location'], as_index=False)
print(df2)
df2.plot(x='Period', y = 'score', ylim=(0,11))#IDK about ylim being necessary 
plt.title('Location', color='black')
plt._show()

Plots

1 Answers

Get the axes retured by df2.plot, and since you're grouping by Location you'll have something similar to:

   Location                                 NaN
0 Location1  AxesSubplot(0.125,0.11;0.775x0.77)
1 Location2  AxesSubplot(0.125,0.11;0.775x0.77)
2 Location3  AxesSubplot(0.125,0.11;0.775x0.77)

Use the apply function with axis=1 to get current axis and the location. With the axis object use set_title using the Location for each plot.

...
df2.apply(print)
ax = df2.plot(x='Period', y='score', ylim=(0, 11))

ax.apply(lambda x: x[1].set_title(x['Location']), axis=1)

plt.show()
Related