1

I have a large number of CSV files and I need to take a subset of them (in this case 9) and plot the data using Plotly. I have written the following for loop which reads each file creates a dataframe and then plots. However, I am scratching my head on a way to automate adding each plot to each row and column of the subplot. i.e first plot to be in row 1, column 1 / 4th subplot to be in row 2, column 1, 8th subplot to be in row 3, column 2, etc. Any ideas on how to achieve this. The last line needs to be altered (row = idx,col = idx)

os.chdir('D:\GEE\Datasets')
dirlist = os.listdir()

no_of_items = 9
Fig = make_subplots(rows = 3, cols = 3)
for idx,fname in enumerate(dirlist[0:9]):
    Df = pd.read_csv(fname)
    try:
        Df['ts'] = pd.to_datetime(Df['ts'],format = '%d/%m/%Y') 
    except:
        Df['ts'] = pd.to_datetime(Df['ts'],format = '%Y/%m/%d')
    Fig.add_trace(
        go.Scatter(
            x = Df['ts'],
            y = Df['fitted.values'],
            mode = 'lines'
        ),

    row = idx,col = idx

    )

1 Answer 1

4

First, I would be concerned that 0:9 is 10 numbers rather than 9. However, assuming you use 0:8 this would work

import math 
row = idx%3 + 1
col = math.floor(idx/3) + 1

If you use 1:9 just remove the "plus 1"s

Or this if you prefer not to import math

row = idx%3 + 1
col = int(str((idx/3) + 1)[0])

I'm curious how experts do this one as I'm sure there is something more elegant

Sign up to request clarification or add additional context in comments.

Comments

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.