I have the following DF:
JavaScript
x
20
20
1
import pandas as pd
2
df = pd.DataFrame({
3
"a": ["a1", "a1", "a1", "a2", "a2", "a2", "a3", "a3", "a3"],
4
"b": ["b1", "b2", "b3", "b1", "b2", "b3", "b1", "b2", "b3"],
5
"c": [10, 20, 30, 40, 50, 60, 80, 90, 100],
6
"d": [100, 200, 300, 400, 500, 600, 1000, 2000, 3000]
7
})
8
df
9
10
a b c d
11
0 a1 b1 10 100
12
1 a1 b2 20 200
13
2 a1 b3 30 300
14
3 a2 b1 40 400
15
4 a2 b2 50 500
16
5 a2 b3 60 600
17
6 a3 b1 80 1000
18
7 a3 b2 90 2000
19
8 a3 b3 100 3000
20
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
1
28
28
1
from plotly import graph_objects as go
2
3
df1=df.query("a=='a1'")
4
fig1 = go.Figure(data=[
5
go.Bar(name = "ccc", x=df1.b, y=df1.c),
6
go.Bar(name = "ddd", x=df1.b, y=df1.d)
7
8
])
9
fig1.update_layout(barmode='group', title="fig1 for a1")
10
11
12
df2=df.query("a=='a2'")
13
fig2 = go.Figure(data=[
14
go.Bar(name = "ccc", x=df2.b, y=df2.c),
15
go.Bar(name = "ddd", x=df2.b, y=df2.d)
16
17
])
18
fig2.update_layout(barmode='group', title="fig2 for a2")
19
20
21
df3=df.query("a=='a3'")
22
fig3 = go.Figure(data=[
23
go.Bar(name = "ccc", x=df3.b, y=df3.c),
24
go.Bar(name = "ddd", x=df3.b, y=df3.d)
25
26
])
27
fig3.update_layout(barmode='group', title="fig3 for a3")
28
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:
- Slice your dataframe using
frames = df['a'].unique()
, - loop through your subsets using
for i, f in enumerate(frames):
, - build figures as normal using
fig=go.Figure()
- 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
1
2
1
figs['fig1'].show()
2
Plot
Complete code
JavaScript
1
20
20
1
import pandas as pd
2
from plotly import graph_objects as go
3
df = pd.DataFrame({
4
"a": ["a1", "a1", "a1", "a2", "a2", "a2", "a3", "a3", "a3"],
5
"b": ["b1", "b2", "b3", "b1", "b2", "b3", "b1", "b2", "b3"],
6
"c": [10, 20, 30, 40, 50, 60, 80, 90, 100],
7
"d": [100, 200, 300, 400, 500, 600, 1000, 2000, 3000]
8
})
9
10
frames = df['a'].unique() # use to slice dataframe
11
figs = {} # container for figures
12
for i, f in enumerate(frames, start = 1):
13
di = df[df['a']==f]
14
fig = go.Figure()
15
fig.add_bar(name = "ccc", x=di.b, y=di.c)
16
fig.add_bar(name = "ddd", x=di.b, y=di.d)
17
fig.update_layout(barmode='group', title="fig" + str(i) + " for a" + str(i))
18
figs['fig'+str(i)] = fig
19
figs['fig1'].show()
20