Skip to content
Advertisement

How do I loop over multiple figures in plotly?

I have the following DF:

JavaScript

I want to create 3 figures for column a: a1, a2 and a3. In the x-axis, for each graph, I have the same b1, b2 and b3. I want to use a loop instead of the code below, which is repetitive because the x-axis is the same for all figures (b1, b2, b3) and the data names are the same (ccc and ddd):

JavaScript

How do I create that loop?

Advertisement

Answer

Approach

There are a number of ways you can do this. The real challenge is rather how to reference them later. Here’s how you do it:

  1. Slice your dataframe using frames = df['a'].unique(),
  2. loop through your subsets using for i, f in enumerate(frames):,
  3. build figures as normal using fig=go.Figure()
  4. add each new figure to a dictionary using figs['fig'+str(i)] = fig

Now you can reference and show, for example, figure 1 using:

JavaScript

Plot

enter image description here

Complete code

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement