HelloToEarth
HelloToEarth

Reputation: 2117

Plotting on specific column values in Python

I've got values that repeat by the HOUR (0-23) for every month (1-12) in every year like:

Year    Month     HOUR  NAME            RATE
2010    1          0    Big              2  
2010    1          0    Channelview      4
2010    1          0    Cottonwood       12
2010    1          1    Big              4  
2010    1          1    Channelview      9
2010    1          1    Cottonwood       11
.
.
.
2010    2          0    Big              6  
2010    2          0    Channelview      10
2010    2          0    Cottonwood       17
.
.
2013    1          0    Big              4  
2013    1          0    Channelview      9
2013    1          0    Cottonwood       11

I'd like to plot this RATE data (y-axis) by the HOUR (x-axis) for the NAME for each month in the year (goes for 7 years). Is there a way in doing this by .groupby or .loc without having to create extra dataframes based off the year and month?

Upvotes: 2

Views: 9126

Answers (1)

sacuL
sacuL

Reputation: 51335

You can do this using groupby:

for name, data in df.groupby('NAME'):
    plt.plot(data['HOUR'], data['RATE'], label=name)

plt.xlabel('Hour')
plt.ylabel('Rate')
plt.legend()
plt.show()

enter image description here

[EDIT] Based on your comments, to create and save a separate plot for each name, you can do something like:

for name, data in df.groupby('NAME'):
    plt.plot(data['HOUR'], data['RATE'], label=name)
    plt.xlabel('Hour')
    plt.ylabel('Rate')
    plt.legend()
    plt.savefig('plot_{}.png'.format(name))
    plt.close()

Upvotes: 5

Related Questions