HelloToEarth
HelloToEarth

Reputation: 2117

Plotting for repeated values using loops Python

I have some data that looks like data = pd.read_csv(....):

Year    Month     HOUR  NAME            RATE
2010    1          0    Big              222  
2010    1          0    Welsch Power     434
2010    1          0    Cottonwood       124
2010    1          1    Big              455  
2010    1          1    Welsch Power     900
2010    1          1    Cottonwood       110
.
.
.
2010    2          0    Big              600  
2010    2          0    Welsch Power     1000
2010    2          0    Cottonwood       170
.
.
2010    3          0    Big              400  
2010    3          0    Welsch Power     900
2010    3          0    Cottonwood       110

As you can see the HOUR ( 0 - 23 ) repeats itself every Month ( 0 - 12 ). I need a way to loop through values so I can plot the RATE (Y-Axis) every Month by the HOUR (X-Axis) for each NAME.

My attempt looks like:

for name, data in data.groupby('NAME'):
    fig = plt.figure(figsize=(14,23))
    plt.subplot(211)
    plt.plot(data['HOUR'], data['RATE'], label=name)
    plt.xlabel('Hour')
    plt.ylabel('Rate')
    plt.legend()
    plt.show()
    plt.close()

This works but because HOUR repeats every change in month the graphs end up back at 0 every time it loops. I want to have each of the 12 Months as separate lines in different colors for each NAME on one graph but currently they look like this:

enter image description here

Upvotes: 1

Views: 1109

Answers (1)

ALollz
ALollz

Reputation: 59519

.pivot your DataFrame after the groupby so it will plot each month as a different line:

import matplotlib.pyplot as plt

for name, gp in df.groupby(['NAME']):
    fig, ax = plt.subplots()
    gp.pivot(index='HOUR', columns='Month', values='RATE').plot(ax=ax, marker='o', title=name)
    plt.show()

enter image description here enter image description here enter image description here

Upvotes: 1

Related Questions