For each unique value in pandas dataframe column, make a go.Figure and scatter t

Viewed 776

I have a dataframe somewhat like so:

Date | Category | Number | Number2 | Etc. |

I want to take every unique value in Category, and plot a line graph with the first Number column, with Date as the X axis. For now I was thinking of doing indiviudal go.Figures, but I may condense it into one graph if it isn't too noisy.

First I tried taking a list of uniques with:

listOfUniques = df['Category'].unique()

and passing that to a for loop, but I quickly realised that was the wrong approach. Then I tried to make a dictionary based on the unique values:

df1 = dict()
for k, v in df.groupby('Category'):
df1[k] = v

but I also could not figure out how to then take the dictionary entries and make a plot for each entry, and it seems like there must be a simpler operation for querying the original df. Let me know if I can give any other information that would help with an answer.

Also, I will probably want to evaluate the numbers conditionally as the percent of some other number in some other column, such that if it is not above, say, 25% of value Y, do not make the plot. I will probably add Y as another column in the original df. Thank you!

1 Answers

I don't think your first approach is too bad---probably not the most efficient method, but can definitely get the job done.

    listOfUniques = df['Category'].unique()
    for unique in listOfUniques.values():
        tempdf = df[ df['Category'] == unique]
        plt.plot(tempdf['Date'], tempdf['Number'], label=unique)
        ###Uncomment this line if you don't want them all on the same graph. 
        ###plt.show()
    plt.show()

Depending on what your data is like this is a viable method.

Related