简体   繁体   中英

Creating plotly subplots using a for loop

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. ie 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

    )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM