Shoaibkhanz
Shoaibkhanz

Reputation: 2082

how to make subplots programmatically in plotly?

I am looking to create something like below using plotly, I have just started playing with the library. I am able create figures using the code below, however I cannot bring them under one figure as in the image.

enter image description here

from sklearn.datasets import load_iris
from sklearn import tree
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pdb 

#n_classes = 3
#plot_colors = "ryb"
plot_step = 0.02
#pair = [0, 1]

iris = load_iris()

for index, pair in enumerate([[0, 1], [0, 2], [0, 3],[1, 2], [1, 3], [2, 3]]):
    fig = make_subplots(rows=2,cols = 3)
    i = (index//3)+1 #indexing for rows
    k =(index//2)+1 #indexing for cols
    #pdb.set_trace()
    X = iris.data[:, pair]
    y = iris.target
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(X, y)

    x_min, x_max = X[:, 0].min(), X[:, 0].max() 
    y_min, y_max = X[:, 1].min(), X[:, 1].max() 
    xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                        np.arange(y_min, y_max, plot_step))

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    #pdb.set_trace()
    
    fig.add_trace(go.Contour(z = Z, 
                            x = np.linspace(x_min,x_max,num = Z.shape[1]),
                            y = np.linspace(y_min,y_max,num = Z.shape[0])
                            
                            ),i,k)
    fig.update_layout(
        autosize=False,
        width=1000,
        height=800)
    for cl in np.unique(y):
        idx = np.where(y == cl)
        fig.add_trace(go.Scatter(x=X[idx, 0].ravel(), y=X[idx, 1].ravel(),
                                    mode = 'markers'),i,k)

fig.show()

Upvotes: 2

Views: 515

Answers (2)

Shoaibkhanz
Shoaibkhanz

Reputation: 2082

from sklearn.datasets import load_iris
from sklearn import tree
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pdb 

plot_step = 0.02

iris = load_iris()
fig = make_subplots(rows=2,cols = 3)
for index, pair in enumerate([[0, 1], [0, 2], [0, 3],[1, 2], [1, 3], [2, 3]]):
    
    i = (index//3)+1 #indexing for rows
    k = (index%3)+1 #indexing for cols
    #pdb.set_trace()
    X = iris.data[:, pair]
    y = iris.target
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(X, y)

    x_min, x_max = X[:, 0].min()-1, X[:, 0].max()+1 
    y_min, y_max = X[:, 1].min()-1, X[:, 1].max()+1 
    xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                        np.arange(y_min, y_max, plot_step))

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    
    
    fig.add_trace(go.Contour(z = Z, 
                            x = np.linspace(x_min,x_max,num = Z.shape[1]),
                            y = np.linspace(y_min,y_max,num = Z.shape[0])
                            ),row = i,col = k)
    
    for cl,cl_name in enumerate(iris.target_names):
        idx = np.where(y == cl)
        fig.add_trace(go.Scatter(x=X[idx, 0].ravel(), y=X[idx, 1].ravel(),
                                    mode = 'markers', 
                                    name = cl_name,
                                    #legendgroup="group1",
                                    #marker=dict(color = ''),
                                    showlegend=False),row = i,col = k)
    #pdb.set_trace()
fig.update_layout(
    autosize=False,
    width=1000,
    height=800)
fig.show()
fig.write_html('plotly101.html')
  • moved make_subplots and update_layout outside as suggested in the previous answer @r-beginners
  • initialised i and k correctly

enter image description here

Upvotes: 1

r-beginners
r-beginners

Reputation: 35115

The reason for the error is that the initial settings for drawing the graph are in a loop process.

Code Change:

  1. The value of pair in a loop process.
  2. move the initial graph setting out of the loop.
  3. change the placement index of `add_trace()
from sklearn.datasets import load_iris
from sklearn import tree
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pdb 

#n_classes = 3
#plot_colors = "ryb"
plot_step = 0.02
#pair = [0, 1]

iris = load_iris()

fig = make_subplots(rows=2,cols = 3) # update
    
for index, pair in enumerate([[0, 1], [0, 2], [0, 3],[1, 1], [1, 2], [1, 3]]):
#     fig = make_subplots(rows=2,cols = 3)
    i = (index//6)+1 #indexing for rows
    k =(index//3)+1 #indexing for rows
    #pdb.set_trace()
    X = iris.data[:, pair]
    y = iris.target
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(X, y)

    x_min, x_max = X[:, 0].min(), X[:, 0].max() 
    y_min, y_max = X[:, 1].min(), X[:, 1].max() 
    xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                        np.arange(y_min, y_max, plot_step))

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    #pdb.set_trace()
    
    fig.add_trace(go.Contour(z = Z, 
                            x = np.linspace(x_min,x_max,num = Z.shape[1]),
                            y = np.linspace(y_min,y_max,num = Z.shape[0]),         
                            ),row=pair[0]+1, col=pair[1])

    for cl in np.unique(y):
        idx = np.where(y == cl)
        fig.add_trace(go.Scatter(x=X[idx, 0].ravel(), y=X[idx, 1].ravel(),
                                    mode = 'markers'),row=pair[0]+1, col=pair[1])
fig.update_layout(
    autosize=False,
    width=1000,
    height=800)

fig.show()

enter image description here

Upvotes: 1

Related Questions