2

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?

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

6 Comments

Awesome. What if I wanted to separate each NAME per plot as a big collection of plots? The scaling is pretty bad and I don't have just 3 names (actually have 20) so it becomes quite a mess.
You can save each plot within the loop, making sure you close the plotting window at each iteration (using plt.close()).
I've tried closing after every iteration of the loop by trying to add plt.figure() before plt.plot() and plt.close() afterwards. Logically it makes sense but it doesn't seem to work. It simply repeats the same NAME values for every plot but changes the actual name in the legend.
It doesn't. Gives the same results as the previous change. I've also adjusted my question data form which might help clarify the issue. The hour repeats for every month of the year so I may need another loop.
With your edits, this should become a separate question, as it was not originally addressed in your question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.