Home > OS >  How to dynamically plot multiple subplots in Python?
How to dynamically plot multiple subplots in Python?

Time:11-15

I need to plot a variable number of plots (at least 1 but it isn't known the number max) and I couldn't come up with a way to dynamically create and assign subplots to the given graphs.

The code looks like this:

check = False
    
    if "node_x_9" in names:
        if "node_x_11" in names:
            plt.plot(df["node_x_9"], df["node_x_11"])
            check = True
    elif "node_x_10" in names:
        if "node_x_12" in names:
            plt.plot(df["node_x_10", "node_x_12"])
            check = True
        
    if check:
        plt.show()

I thought about presetting a number of subplots (e.g. plt.subplots(3, 3)) but I still could not come up with a way to assign the plots without bounding them to a given subplot position.

My idea would be to create a 2x1 plot if I have two subplots, 1x1 if I have one, 3x1 if I have 3 and so on and not letting any subplot space empty.

CodePudding user response:

I've come across cases like this, you want to generate one plot per case, but don't know how many cases exist until you query the data on the day.

I used a square layout as an assumption (alter the below if you require a different aspect ratio) then count how many cases you have - find the integer square-root, which, plus one, will give you the integer side-length of a square that is guaranteed to fit your requirements.

Now, you can establish a matplotlib example plot layout

  • Related