Esempio n. 1
0
    def test_get_subplot_out_of_bounds(self):
        fig = subplots.make_subplots(rows=4, cols=2)

        self.assertRaises(ValueError, lambda: fig.get_subplot(0, 1))
        self.assertRaises(ValueError, lambda: fig.get_subplot(5, 1))
        self.assertRaises(ValueError, lambda: fig.get_subplot(1, 0))
        self.assertRaises(ValueError, lambda: fig.get_subplot(1, 3))
 def setUp(self):
     self.fig = make_subplots(rows=2,
                              cols=2,
                              specs=[[{}, {
                                  "secondary_y": True
                              }], [{}, {
                                  "type": "polar"
                              }]])
    def setUp(self):
        fig = make_subplots(
            rows=3,
            cols=3,
            specs=[
                [{}, {
                    "type": "scene"
                }, {}],
                [{
                    "secondary_y": True
                }, {
                    "type": "polar"
                }, {
                    "type": "polar"
                }],
                [{
                    "type": "xy",
                    "colspan": 2
                }, None, {
                    "type": "ternary"
                }],
            ],
        ).update(layout={"height": 800})

        fig.layout.xaxis.title.text = "A"
        fig.layout.xaxis2.title.text = "A"
        fig.layout.xaxis3.title.text = "B"
        fig.layout.xaxis4.title.text = "B"

        fig.layout.yaxis.title.text = "A"
        fig.layout.yaxis2.title.text = "B"
        fig.layout.yaxis3.title.text = "A"
        fig.layout.yaxis4.title.text = "B"

        fig.layout.polar.angularaxis.rotation = 45
        fig.layout.polar2.angularaxis.rotation = 45
        fig.layout.polar.radialaxis.title.text = "A"
        fig.layout.polar2.radialaxis.title.text = "B"

        fig.layout.scene.xaxis.title.text = "A"
        fig.layout.scene.yaxis.title.text = "B"

        fig.layout.ternary.aaxis.title.text = "A"

        self.fig = fig
        self.fig_no_grid = go.Figure(self.fig.to_dict())
Esempio n. 4
0
    def setUp(self):
        fig = make_subplots(
            rows=3,
            cols=2,
            specs=[
                [{}, {"type": "scene"}],
                [{"secondary_y": True}, {"type": "polar"}],
                [{"type": "domain", "colspan": 2}, None],
            ],
        ).update(layout={"height": 800})

        # data[0], (1, 1)
        fig.add_scatter(
            mode="markers",
            y=[2, 3, 1],
            name="A",
            marker={"color": "green", "size": 10},
            row=1,
            col=1,
        )

        # data[1], (1, 1)
        fig.add_bar(y=[2, 3, 1], row=1, col=1, name="B")

        # data[2], (2, 1)
        fig.add_scatter(
            mode="lines", y=[1, 2, 0], line={"color": "purple"}, name="C", row=2, col=1
        )

        # data[3], (2, 1)
        fig.add_heatmap(z=[[2, 3, 1], [2, 1, 3], [3, 2, 1]], row=2, col=1, name="D")

        # data[4], (1, 2)
        fig.add_scatter3d(
            x=[0, 0, 0],
            y=[0, 0, 0],
            z=[0, 1, 2],
            mode="markers",
            marker={"color": "green", "size": 10},
            name="E",
            row=1,
            col=2,
        )

        # data[5], (1, 2)
        fig.add_scatter3d(
            x=[0, 0, -1],
            y=[-1, 0, 0],
            z=[0, 1, 2],
            mode="lines",
            line={"color": "purple", "width": 4},
            name="F",
            row=1,
            col=2,
        )

        # data[6], (2, 2)
        fig.add_scatterpolar(
            mode="markers",
            r=[0, 3, 2],
            theta=[0, 20, 87],
            marker={"color": "green", "size": 8},
            name="G",
            row=2,
            col=2,
        )

        # data[7], (2, 2)
        fig.add_scatterpolar(
            mode="lines", r=[0, 3, 2], theta=[20, 87, 111], name="H", row=2, col=2
        )

        # data[8], (3, 1)
        fig.add_parcoords(
            dimensions=[{"values": [1, 2, 3, 2, 1]}, {"values": [3, 2, 1, 3, 2, 1]}],
            line={"color": "purple"},
            name="I",
            row=3,
            col=1,
        )

        # data[9], (2, 1) with secondary_y
        fig.add_scatter(
            mode="lines",
            y=[1, 2, 0],
            line={"color": "purple"},
            name="C",
            row=2,
            col=1,
            secondary_y=True,
        )

        self.fig = fig
        self.fig_no_grid = go.Figure(self.fig.to_dict())
Esempio n. 5
0
def _facet_grid(
    df,
    x,
    y,
    facet_row,
    facet_col,
    num_of_rows,
    num_of_cols,
    facet_row_labels,
    facet_col_labels,
    trace_type,
    flipped_rows,
    flipped_cols,
    show_boxes,
    SUBPLOT_SPACING,
    marker_color,
    kwargs_trace,
    kwargs_marker,
):

    fig = make_subplots(
        rows=num_of_rows,
        cols=num_of_cols,
        shared_xaxes=True,
        shared_yaxes=True,
        horizontal_spacing=SUBPLOT_SPACING,
        vertical_spacing=SUBPLOT_SPACING,
        print_grid=False,
    )
    annotations = []
    if not facet_row and not facet_col:
        trace = dict(type=trace_type,
                     marker=dict(color=marker_color,
                                 line=kwargs_marker["line"]),
                     **kwargs_trace)

        if x:
            trace["x"] = df[x]
        if y:
            trace["y"] = df[y]
        trace = _make_trace_for_scatter(trace, trace_type, marker_color,
                                        **kwargs_marker)

        fig.append_trace(trace, 1, 1)

    elif (facet_row and not facet_col) or (not facet_row and facet_col):
        groups_by_facet = list(
            df.groupby(facet_row if facet_row else facet_col))
        for j, group in enumerate(groups_by_facet):
            trace = dict(type=trace_type,
                         marker=dict(color=marker_color,
                                     line=kwargs_marker["line"]),
                         **kwargs_trace)

            if x:
                trace["x"] = group[1][x]
            if y:
                trace["y"] = group[1][y]
            trace = _make_trace_for_scatter(trace, trace_type, marker_color,
                                            **kwargs_marker)

            fig.append_trace(trace, j + 1 if facet_row else 1,
                             1 if facet_row else j + 1)

            label = _return_label(
                group[0],
                facet_row_labels if facet_row else facet_col_labels,
                facet_row if facet_row else facet_col,
            )

            annotations.append(
                _annotation_dict(
                    label,
                    num_of_rows - j if facet_row else j + 1,
                    num_of_rows if facet_row else num_of_cols,
                    SUBPLOT_SPACING,
                    "row" if facet_row else "col",
                    flipped_rows,
                ))

    elif facet_row and facet_col:
        groups_by_facets = list(df.groupby([facet_row, facet_col]))
        tuple_to_facet_group = {item[0]: item[1] for item in groups_by_facets}

        row_values = df[facet_row].unique()
        col_values = df[facet_col].unique()
        for row_count, x_val in enumerate(row_values):
            for col_count, y_val in enumerate(col_values):
                try:
                    group = tuple_to_facet_group[(x_val, y_val)]
                except KeyError:
                    group = pd.DataFrame([[None, None]], columns=[x, y])
                trace = dict(type=trace_type,
                             marker=dict(color=marker_color,
                                         line=kwargs_marker["line"]),
                             **kwargs_trace)
                if x:
                    trace["x"] = group[x]
                if y:
                    trace["y"] = group[y]
                trace = _make_trace_for_scatter(trace, trace_type,
                                                marker_color, **kwargs_marker)

                fig.append_trace(trace, row_count + 1, col_count + 1)
                if row_count == 0:
                    label = _return_label(col_values[col_count],
                                          facet_col_labels, facet_col)
                    annotations.append(
                        _annotation_dict(
                            label,
                            col_count + 1,
                            num_of_cols,
                            SUBPLOT_SPACING,
                            row_col="col",
                            flipped=flipped_cols,
                        ))

            label = _return_label(row_values[row_count], facet_row_labels,
                                  facet_row)
            annotations.append(
                _annotation_dict(
                    label,
                    num_of_rows - row_count,
                    num_of_rows,
                    SUBPLOT_SPACING,
                    row_col="row",
                    flipped=flipped_rows,
                ))

    return fig, annotations
Esempio n. 6
0
def get_subplots(rows=1,cols=1,
				  shared_xaxes=False, shared_yaxes=False,
				  start_cell='top-left', theme=None,base_layout=None,
				  **kwargs):

	"""
	Generates a subplot view for a set of figures

	Parameters:
	-----------
		rows : int
			Number of rows
		cols : int
			Number of cols
		shared_xaxes : bool
			Assign shared x axes.
			If True, subplots in the same grid column have one common
			shared x-axis at the bottom of the gird.
		shared_yaxes : bool
			Assign shared y axes.
			If True, subplots in the same grid row have one common
			shared y-axis on the left-hand side of the gird.
		start_cell : string
				'bottom-left'
				'top-left'
			Choose the starting cell in the subplot grid used to set the
			domains of the subplots.
		theme : string
			Layout Theme
				solar
				pearl
				white
			see cufflinks.getThemes() for all
			available themes
		horizontal_spacing : float
				[0,1]
			Space between subplot columns.
		vertical_spacing : float
			Space between subplot rows.
		specs : list of dicts
			Subplot specifications.
				ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
				ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]

			- Indices of the outer list correspond to subplot grid rows
			  starting from the bottom. The number of rows in 'specs'
			  must be equal to 'rows'.

			- Indices of the inner lists correspond to subplot grid columns
			  starting from the left. The number of columns in 'specs'
			  must be equal to 'cols'.

			- Each item in the 'specs' list corresponds to one subplot
			  in a subplot grid. (N.B. The subplot grid has exactly 'rows'
			  times 'cols' cells.)

			- Use None for blank a subplot cell (or to move pass a col/row span).

			- Note that specs[0][0] has the specs of the 'start_cell' subplot.

			- Each item in 'specs' is a dictionary.
				The available keys are:

				* is_3d (boolean, default=False): flag for 3d scenes
				* colspan (int, default=1): number of subplot columns
					for this subplot to span.
				* rowspan (int, default=1): number of subplot rows
					for this subplot to span.
				* l (float, default=0.0): padding left of cell
				* r (float, default=0.0): padding right of cell
				* t (float, default=0.0): padding right of cell
				* b (float, default=0.0): padding bottom of cell

			- Use 'horizontal_spacing' and 'vertical_spacing' to adjust
			  the spacing in between the subplots.

		insets : list of dicts
			Inset specifications.

			- Each item in 'insets' is a dictionary.
				The available keys are:

				* cell (tuple, default=(1,1)): (row, col) index of the
					subplot cell to overlay inset axes onto.
				* is_3d (boolean, default=False): flag for 3d scenes
				* l (float, default=0.0): padding left of inset
					  in fraction of cell width
				* w (float or 'to_end', default='to_end') inset width
					  in fraction of cell width ('to_end': to cell right edge)
				* b (float, default=0.0): padding bottom of inset
					  in fraction of cell height
				* h (float or 'to_end', default='to_end') inset height
					  in fraction of cell height ('to_end': to cell top edge)
	"""

	if not theme:
		theme = auth.get_config_file()['theme']

	layout= base_layout if base_layout else getLayout(theme,**check_kwargs(kwargs,__LAYOUT_AXIS))
	sp=make_subplots(rows=rows,cols=cols,shared_xaxes=shared_xaxes,
										   shared_yaxes=shared_yaxes,print_grid=False,
											start_cell=start_cell,**kwargs)
	sp, grid_ref = sp.to_dict(), sp._grid_ref

	for k,v in list(layout.items()):
		if 'xaxis' not in k and 'yaxis' not in k:
			sp['layout'].update({k:v})

	def update_axis(fig,layout):
		for axis, n in list(Figure(fig).axis['len'].items()):
			for _ in range(1,n+1):
				for k,v in list(layout['{0}axis'.format(axis)].items()):
					_='' if _==1 else _
					if k not in fig['layout']['{0}axis{1}'.format(axis,_)]:
						fig['layout']['{0}axis{1}'.format(axis,_)][k]=v

	update_axis(sp,layout)
	# 124 - zeroline on the first figure

	# if 'subplot_titles' in kwargs:
	# 	if 'annotations' in layout:
	# 		annotation=sp['layout']['annotations'][0]
	# 	else:
	# 		annotation=getLayout(theme,annotations=[Annotation(text='')])['annotations']
	# 	for ann in sp['layout']['annotations']:
	# 		ann.update(font=dict(color=annotation['font']['color']))

	# def update_items(sp_item,layout,axis):
	# 	for k,v in list(layout[axis].items()):
	# 		sp_item.update({k:v})

	# for k,v in list(sp['layout'].items()):
	# 	if isinstance(v,go.XAxis):
	# 		update_items(v,layout,'xaxis1')
	# 	elif isinstance(v,go.YAxis):
	# 		update_items(v,layout,'xaxis1')




	return sp, grid_ref
Esempio n. 7
0
    def test_get_subplot(self):
        # Make Figure with subplot types
        fig = subplots.make_subplots(
            rows=4,
            cols=2,
            specs=[
                [{}, {"secondary_y": True}],
                [{"type": "polar"}, {"type": "ternary"}],
                [{"type": "scene"}, {"type": "geo"}],
                [{"type": "domain", "colspan": 2}, None],
            ],
        )

        fig.add_scatter(y=[2, 1, 3], row=1, col=1)
        fig.add_scatter(y=[2, 1, 3], row=1, col=2)
        fig.add_scatter(y=[1, 3, 2], row=1, col=2, secondary_y=True)
        fig.add_trace(go.Scatterpolar(r=[2, 1, 3], theta=[20, 50, 125]), row=2, col=1)
        fig.add_traces(
            [go.Scatterternary(a=[0.2, 0.1, 0.3], b=[0.4, 0.6, 0.5])],
            rows=[2],
            cols=[2],
        )
        fig.add_scatter3d(
            x=[2, 0, 1], y=[0, 1, 0], z=[0, 1, 2], mode="lines", row=3, col=1
        )
        fig.add_scattergeo(lat=[0, 40], lon=[10, 5], mode="lines", row=3, col=2)
        fig.add_parcats(
            dimensions=[
                {"values": ["A", "A", "B", "A", "B"]},
                {"values": ["a", "a", "a", "b", "b"]},
            ],
            row=4,
            col=1,
        )

        fig.update_traces(uid=None)
        fig.update(layout_height=1200)

        # Check
        expected = Figure(
            {
                "data": [
                    {"type": "scatter", "xaxis": "x", "y": [2, 1, 3], "yaxis": "y"},
                    {"type": "scatter", "xaxis": "x2", "y": [2, 1, 3], "yaxis": "y2"},
                    {"type": "scatter", "xaxis": "x2", "y": [1, 3, 2], "yaxis": "y3"},
                    {
                        "r": [2, 1, 3],
                        "subplot": "polar",
                        "theta": [20, 50, 125],
                        "type": "scatterpolar",
                    },
                    {
                        "a": [0.2, 0.1, 0.3],
                        "b": [0.4, 0.6, 0.5],
                        "subplot": "ternary",
                        "type": "scatterternary",
                    },
                    {
                        "mode": "lines",
                        "scene": "scene",
                        "type": "scatter3d",
                        "x": [2, 0, 1],
                        "y": [0, 1, 0],
                        "z": [0, 1, 2],
                    },
                    {
                        "geo": "geo",
                        "lat": [0, 40],
                        "lon": [10, 5],
                        "mode": "lines",
                        "type": "scattergeo",
                    },
                    {
                        "dimensions": [
                            {"values": ["A", "A", "B", "A", "B"]},
                            {"values": ["a", "a", "a", "b", "b"]},
                        ],
                        "domain": {"x": [0.0, 0.9400000000000001], "y": [0.0, 0.19375]},
                        "type": "parcats",
                    },
                ],
                "layout": {
                    "geo": {
                        "domain": {
                            "x": [0.5700000000000001, 0.9400000000000001],
                            "y": [0.26875, 0.4625],
                        }
                    },
                    "height": 1200,
                    "polar": {"domain": {"x": [0.0, 0.37], "y": [0.5375, 0.73125]}},
                    "scene": {"domain": {"x": [0.0, 0.37], "y": [0.26875, 0.4625]}},
                    "ternary": {
                        "domain": {
                            "x": [0.5700000000000001, 0.9400000000000001],
                            "y": [0.5375, 0.73125],
                        }
                    },
                    "xaxis": {"anchor": "y", "domain": [0.0, 0.37]},
                    "xaxis2": {
                        "anchor": "y2",
                        "domain": [0.5700000000000001, 0.9400000000000001],
                    },
                    "yaxis": {"anchor": "x", "domain": [0.80625, 1.0]},
                    "yaxis2": {"anchor": "x2", "domain": [0.80625, 1.0]},
                    "yaxis3": {"anchor": "x2", "overlaying": "y2", "side": "right"},
                },
            }
        )

        expected.update_traces(uid=None)

        # Make sure we have expected starting figure
        self.assertEqual(fig, expected)

        # (1, 1)
        subplot = fig.get_subplot(1, 1)
        self.assertEqual(
            subplot, SubplotXY(xaxis=fig.layout.xaxis, yaxis=fig.layout.yaxis)
        )

        # (1, 2) Primary
        subplot = fig.get_subplot(1, 2)
        self.assertEqual(
            subplot, SubplotXY(xaxis=fig.layout.xaxis2, yaxis=fig.layout.yaxis2)
        )

        # (1, 2) Primary
        subplot = fig.get_subplot(1, 2, secondary_y=True)
        self.assertEqual(
            subplot, SubplotXY(xaxis=fig.layout.xaxis2, yaxis=fig.layout.yaxis3)
        )

        # (2, 1)
        subplot = fig.get_subplot(2, 1)
        self.assertEqual(subplot, fig.layout.polar)

        # (2, 2)
        subplot = fig.get_subplot(2, 2)
        self.assertEqual(subplot, fig.layout.ternary)

        # (3, 1)
        subplot = fig.get_subplot(3, 1)
        self.assertEqual(subplot, fig.layout.scene)

        # (3, 2)
        subplot = fig.get_subplot(3, 2)
        self.assertEqual(subplot, fig.layout.geo)

        # (4, 1)
        subplot = fig.get_subplot(4, 1)
        domain = fig.data[-1].domain
        self.assertEqual(subplot, SubplotDomain(x=domain.x, y=domain.y))
Esempio n. 8
0
    def plot_resultats(self,
                       col=pcol.sequential.Bluered,
                       d3=False,
                       share_xaxes=True,
                       share_yaxes=True,
                       hideUpper=False,
                       zmaxHisto=4,
                       offset=0,
                       iloc=slice(None),
                       loc=slice(None),
                       nb=None,
                       max3d=15,
                       begin3d=0,
                       offset3d=0,
                       scatterColorBarX=-0.2,
                       mesh3d=True):
        obj = self.obj
        resu = obj.resultat
        yy = resu >> df_.select(df_.starts_with("param_"), "mean_test_score")
        yy["mean_test_score"] = np.round(yy["mean_test_score"] * 100, 2)
        nb = nb if nb is not None else np.shape(yy)[1] - 1
        nbo = min(nb + offset, nb)
        yyX = yy.iloc[:, :-1].iloc[:, offset:nbo].loc[:, loc].iloc[:, iloc]
        yyX["mean_test_score"] = yy["mean_test_score"]
        yy = yyX
        yy_ = yy.fillna("`None`")
        yl = yy["mean_test_score"]
        cmax = max(yl)
        cmin = min(yl)

        # yy=yy.fillna("`None`")
        yy = yy_.apply(lambda x: namesEscape(x.values), axis=0)
        # print(yy)
        yy["mean_test_score"] = yl
        yy2 = yy
        # print(yy)
        nb = np.shape(yy)[1]
        nb1 = nb - 1
        nbCols = nb1
        ff2 = yy.columns.tolist()[:-1]
        if d3:
            nbCols -= 2
            if nbCols == 0:
                raise Exception("if 3D -> minimun 3 params")
            comb = list(combinations(
                range(nb1), 3))[(begin3d + offset3d):(max3d + offset3d)]
            # Initialize figure with 4 3D subplots
            images_per_row = min(len(comb), nbCols)
            n_rows = (len(comb) - 1) // images_per_row + 1

            # print(comb)
            # print(n_rows)
            # print(images_per_row)
            spco = np.full((n_rows, images_per_row), [{
                'type': 'scatter3d'
            }]).tolist()
            fig = make_subplots(vertical_spacing=0.01,
                                horizontal_spacing=0.01,
                                rows=n_rows,
                                cols=images_per_row,
                                specs=spco)
            iio = 0
            lay = {}
            ip = None
            for i in range(n_rows):
                for j in range(images_per_row):
                    # print(i+1,j+1,iio)
                    com1 = comb[iio]
                    x = ff2[com1[0]]
                    y = ff2[com1[1]]
                    z = ff2[com1[2]]
                    # print(x,y,z)
                    opX = px.scatter_3d(yy_,
                                        x=x,
                                        color_continuous_scale="Bluered",
                                        y=y,
                                        z=z,
                                        color="mean_test_score")
                    oip = opX["layout"]
                    xxo = "scene" + ("" if iio == 0 else str(iio + 1))
                    oip[xxo] = oip["scene"]
                    if iio != 0:
                        oip["scene"] = None
                    opX["data"][0]["scene"] = "scene" + ("" if iio == 0 else
                                                         str(iio + 1))
                    opX['data'][0]["marker"].cmax = cmax
                    opX['data'][0]["marker"].cmin = cmin
                    # opX["data"][0].hoverlabel=dict(bgcolor=yy_["mean_test_score"])
                    # opX["data"][0]["yaxis"]="y"+("" if i ==0 else str(i+1))
                    oip[xxo]["domain"] = None
                    if iio == 0:
                        ip = oip["coloraxis"]
                    # opX["data"][0]["marker"]["color"]=pcol.sequential.Bluered
                    lay[xxo] = oip[xxo].to_plotly_json()
                    lay[xxo]["aspectmode"] = "cube"
                    fig.append_trace(opX["data"][0], row=i + 1, col=j + 1)
                    fig.append_trace(scatter3D_MESH(
                        x=yy_.loc[:, x],
                        y=yy_.loc[:, y],
                        z=yy_.loc[:, z],
                        cmax=cmax,
                        cmin=cmin,
                        col=yy_.loc[:, "mean_test_score"],
                        onlyMesh=True,
                        visible=mesh3d).data[0],
                                     row=i + 1,
                                     col=j + 1)
                    iio += 1
                    if len(comb) == iio:
                        lay["coloraxis"] = ip
                        fig["layout"] = merge(fig["layout"].to_plotly_json(),
                                              lay,
                                              add=False)
                        return fromCombiToplot(
                            fig.update_layout(showlegend=False), comb,
                            nbCols).update_layout(width=1500,
                                                  height=1500,
                                                  margin=dict(t=300))
            # return fig
            # raise NotImplementedError()
        else:
            # print(yy)

            oo2 = ff.create_scatterplotmatrix(
                yy,
                index="mean_test_score",
                diag='histogram',
                marker=dict(colorbar=dict(x=scatterColorBarX,
                                          ticktextside="left",
                                          title="mean_test_score"),
                            showscale=True),
                colormap=col,
                width=1000,
                height=1000,
                hovertemplate="<b>%{marker.color}%</b><br>" + "x : %{x}<br>" +
                "y : %{y}<br>" + "<extra></extra>",
                size=17).update_yaxes(automargin=True).update_xaxes(
                    automargin=True)
            ii = 0
            oo = oo2.data
            # print()
            diago = 0

            od2 = list(oo2.data)
            gh = True
            gh2 = True
            # df2=
            mmax = 0
            mmin = 0
            for i in range(1, nb):
                for k in range(1, nb):
                    if i < k:
                        xx = yy_.iloc[:, k - 1]
                        dt = od2[ii]
                        yy = dt["y"]
                        yy = yy_.iloc[:, i - 1]
                        mmax_ = np.max(
                            pd.crosstab(np.array(yy), np.array(xx)).values)
                        mmin_ = np.min(
                            pd.crosstab(np.array(yy), np.array(xx)).values)
                        mmax = max(mmax, mmax_)
                        mmin = min(mmin, mmin_)
                        ii += 1
            ii = 0
            for i in range(1, nb):
                i1 = i
                x_ticker = ff2[i - 1]
                for k in range(1, nb):
                    y_ticker = ff2[k - 1]
                    k1 = k
                    dt = od2[ii]
                    xx = dt["x"]
                    if i1 < k1:
                        # print(ii)
                        # dt.update(visible=False)
                        xx = yy_.iloc[:, k - 1]
                        yy = dt["y"]
                        # yy=yy.fillna("None")
                        yy = yy_.iloc[:, i - 1]
                        ft = dt.xaxis
                        visible = True
                        if hideUpper:
                            ft = "x2"
                            visible = False
                        zz = pd.crosstab(np.array(yy), np.array(xx))

                        figi = go.Heatmap(  #blueRed
                            colorscale="oranges",
                            showscale=gh,
                            colorbar=dict(x=1.10, title="Count"),
                            zmin=mmin,
                            zmax=mmax,
                            z=zz.values,
                            y=namesEscape(zz.index.tolist()),
                            x=namesEscape(zz.columns.tolist()),
                            xgap=2,
                            ygap=2,
                            xaxis=ft,
                            yaxis=dt.yaxis,
                            visible=visible)
                        gh = False
                        # figi.hoverlabel=dict(bgcolor=zz.values.tolist())
                        # if i1==1:
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii+1)].tickangle=0
                        # if k1 == (nb-1):
                        #     oo2.layout["yaxis{}".format("" if ii==0 else ii+1)].tickvals=namesEscape(zz.index.tolist())
                        # print(ii)
                        # print(od2[ii])
                        # figi.name='{0} vs {1}'.format(x_ticker,y_ticker)
                        od2[ii] = figi

                    if i1 > k1 and gh2:
                        gh2 = False
                        od2[ii].marker.showscale = True

                    if i1 == k1:
                        zr = yy_.iloc[:, k - 1]
                        # print(zr)
                        od2[ii].x = od2[ii].x if isinstance(
                            zr[0], str) else namesEscape(secureSort(zr))
                        uni = unique(od2[ii].x)
                        # print(yy)
                        vl = yy2.groupby(x_ticker).mean().loc[
                            uni, :].values.flatten().tolist()
                        # print(vl)
                        od2[ii].marker.cmin = cmin
                        od2[ii].marker.cmax = cmax
                        od2[ii].marker.color = vl
                        od2[ii].marker.colorscale = "Bluered"
                        od2[ii]["hovertemplate"]="x ["+y_ticker+"]: %{x}<br>" +\
                                                "nb : %{y}<br>" +\
                                                "mean(mean_test_score) : %{marker.color} <br>" +\
                                                "<extra></extra>"
                    od2[ii]["name"] = ""
                    if i1 < k1:
                        od2[ii]["hovertemplate"]="x ["+y_ticker+"]: %{x}<br>" +\
                                                "y ["+x_ticker+"]: %{y}<br>" +\
                                                "nb : %{z} <br>" +\
                                                "<extra></extra>"
                    if i1 > k1:
                        od2[ii]["marker"]["opacity"] = 0.5,
                        # zr=yy_.iloc[:,k-1]
                        # # print(zr)
                        # # print(isinstance(zr[0],str))
                        # od2[ii].x = od2[ii].x# if isinstance(zr[0],str) else namesEscape(secureSort(zr))
                        # # print(od2[ii].x)
                        # zr=yy_.iloc[:,i-1]
                        # # print(zr)
                        # od2[ii].y = od2[ii].y #if isinstance(zr[0],str) else namesEscape(secureSort(zr))

                        xo = yy_.iloc[:, k - 1]  #od2[ii].x
                        yi = yy_.iloc[:, i - 1]  #od2[ii].y
                        colr = od2[ii].marker.color
                        bhh = pd.DataFrame(dict(a=xo, b=yi, z=colr))
                        # print(bhh)
                        bhh2_ = bhh.groupby(["a", "b"], sort=False)
                        bhh2 = bhh2_.mean().reset_index()
                        bhj_ = (bhh2_.count().values).flatten()
                        bhj = [min(10, int(i / 2.)) for i in bhj_]
                        # print(bhj)
                        # raise Exception()
                        od2[ii].x = bhh2.loc[:, "a"]
                        od2[ii].y = bhh2.loc[:, "b"]
                        od2[ii].marker.color = bhh2.loc[:, "z"]
                        od2[ii].marker.line = dict(width=bhj, color='black')
                        od2[ii].customdata = bhj_
                        od2[ii]["hovertemplate"]="x ["+y_ticker+"]: %{x}<br>" +\
                                                "y ["+x_ticker+"]: %{y}<br>" +\
                                                "mean(mean_test_score) : %{marker.color}%<br>nb : %{customdata}" +\
                                                "<extra></extra>"

                        kkop = od2[ii].x
                        kkop2 = od2[ii].y
                        od2[ii].x = namesEscape(od2[ii].x)
                        od2[ii].y = namesEscape(od2[ii].y)
                        # print(od2[ii].x)

                    ii += 1
                    if i1 > k1:
                        zr = kkop.tolist()  #yy_.iloc[:,k-1]
                        # print(zr)
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii+1)].tickangle=0
                        yj = kkop if isinstance(zr[0], str) else namesEscape(
                            secureSort(zr))
                        # print(unique(yj))
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].categoryorder = "array"
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].categoryarray = unique(
                                yj).tolist()
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].type = "category"
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].tickvals = unique(
                                yj).tolist()
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii)].rangemode = 'tozero'
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].range = [
                                0, len(unique(yj).tolist()) - 1
                            ]
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii)].tick0= ''
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii)].tickson='boundaries'#=unique(yj).tolist()
                        # yy=dt["y"]
                        zr = kkop2.tolist()
                        # print(type(zr[0]))
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii+1)].tickangle=0
                        yj2 = zr if isinstance(zr[0], str) else namesEscape(
                            secureSort(zr))
                        # print(unique(yj2))
                        # print(yj2)
                        # oo2.layout["yaxis{}".format("" if ii==0 else ii)].tickvals=unique(yj2).tolist()
                        # oo2.layout["yaxis{}".format("" if ii==0 else ii)].ticktext=unique(yj2).tolist()
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].categoryorder = "array"
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].categoryarray = unique(
                                yj2).tolist()
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].type = "category"
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].tickvals = unique(
                                yj2).tolist()
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].rangemode = 'tozero'
                        # oo2.layout["yaxis{}".format("" if ii==0 else ii)].range= [0, len(unique(yj2).tolist())-1]
                        # gg=list(oo2.data)

                    if i1 < k1 and hideUpper:
                        oo2.layout["xaxis{}".format("" if ii ==
                                                    0 else ii)].ticks = ""
                        oo2.layout["xaxis{}".format("" if ii ==
                                                    0 else ii)].tickvals = []
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].showgrid = False
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].zeroline = False
                        oo2.layout["yaxis{}".format("" if ii ==
                                                    0 else ii)].ticks = ""
                        oo2.layout["yaxis{}".format("" if ii ==
                                                    0 else ii)].tickvals = []
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].showgrid = False
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].zeroline = False

                    ls = list(oo2.layout.annotations)
                    if k1 == i1:
                        u = dt
                        xx = "x{}".format("" if ii == 0 else ii)
                        yy = "y{}".format("" if ii == 0 else ii)
                        ooo = oo2.layout["yaxis{}".format("" if ii ==
                                                          0 else ii)]
                        ooo2 = oo2.layout["xaxis{}".format("" if ii ==
                                                           0 else ii)]
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii)].tickangle=0
                        # print(ooo.domain)
                        texto = ff2[diago]
                        diago += 1
                        ooi = dt["y"]
                        ooi = max(ooo.domain) + 0.01
                        ooi2 = sum(ooo2.domain) / 2.
                        # print(ooo.domain)
                        # print(max(ooo.domain)-min(ooo.domain))
                        oo2.layout.annotations = ls + [
                            dict(yref="paper",
                                 showarrow=F,
                                 x=ooi2,
                                 y=ooi,
                                 xref="paper",
                                 text=texto,
                                 yanchor="bottom",
                                 xanchor="center",
                                 textangle=0)
                        ]
                        # oo2.data[ii].title.text = ff2[]

                    if k1 == 1 or i1 == (nb - 1):
                        # print(ii)
                        oo2.layout["xaxis{}".format("" if ii ==
                                                    0 else ii)].title.text = ""
                        oo2.layout["yaxis{}".format("" if ii ==
                                                    0 else ii)].title.text = ""
                    if share_xaxes and i1 > 1 and i1 < (nb - 1) and i1 != k1:
                        # print(ii)
                        # if k1 >1:
                        oo2.layout["xaxis{}".format(
                            "" if ii == 0 else ii)].showticklabels = F
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii)].tickangle=45
                        # oo2.layout["yaxis{}".format("" if ii==0 else ii)].showticklabels=F
                        # oo2.layout["xaxis{}".format("" if ii==0 else ii)].showgrid=True
                    # if i1==2 and k1==1:
                    # oo2.layout["xaxis{}".format("" if ii==0 else ii)].showticklabels=T
                    if share_yaxes and (i1 == k1 or k1 == (nb - 1)):
                        oo2.layout["yaxis{}".format("" if ii ==
                                                    0 else ii)].side = "right"
                    if share_yaxes and k1 > 1 and i1 != k1 and k1 != (nb - 1):
                        oo2.layout["yaxis{}".format(
                            "" if ii == 0 else ii)].showticklabels = F

                    # if share_yaxes and i1==(k1+1) and k1 > 2 and not oo2.layout["yaxis{}".format("" if ii==0 else ii)].showticklabels:
                    #     oo2.layout["yaxis{}".format("" if ii==0 else ii)].side="right"
                    #     oo2.layout["yaxis{}".format("" if ii==0 else ii)].showticklabels=T

        oo2 = go.Figure(data=od2, layout=oo2.layout)
        return oo2
Esempio n. 9
0
def fromCombiToplot(fig, combi, nbCols=4):
    d = fig.data
    l = fig.layout
    comb = np.array(combi)
    firstrow = len(np.unique(comb[:, 0]))
    dfComb = pd.DataFrame(comb, columns=["f", "s", "t"])
    dfCombGr = dfComb.groupby(["f", "s"])
    dfCombGrG = dfComb.groupby(["f"]).count()
    dfCombGrCount = dfCombGr.count()
    #offset=0
    nrowsG = 0
    ncolsG = 0
    dims = []
    subT = []
    iio = 0
    for j in range(firstrow):
        nbJ = dfCombGrG.loc[j]["s"]
        #datasJ=d[offset:(offset+nbJ)]
        #layoutJ=getLayoutsScene(l,offset,nbJ)
        dfCombGrCountJ = dfCombGrCount.loc[j]
        nbT = dfCombGrCountJ.values.ravel()
        yba = []
        for i_, j2 in enumerate(nbT):
            if i_ == 0:
                tb = [
                    "z : " + l["scene" +
                               ("" if i + iio == 0 else str(i + iio + 1))]
                    ["zaxis"]["title"]["text"] for i in range(j2)
                ]
                #print([""]*(i_+j)+tb+[""]*(nbCols-j2-i_-j))
                yba.append([""] * (i_ + j) + tb + [""] *
                           (nbCols - j2 - i_ - j))
            else:
                yba.append([""] * j2 + [""] * (nbCols - j2))
            nrows, ncols = getNbRowsCols(j2, nbCols)
            dims.append((nrows, ncols))
            nrowsG += nrows
            ncolsG += ncols
            iio += j2
        #subTR=+[""]*(nbCols-j2)
        subT.append(yba)
    #print(nrowsG,nbCols)

    #offset+=nbJ
    #print(subT)
    f = make_subplots(rows=int(nrowsG),
                      horizontal_spacing=0,
                      vertical_spacing=0.05,
                      cols=nbCols,
                      specs=np.full((nrowsG, nbCols), [{
                          'type': 'scene'
                      }]).tolist(),
                      subplot_titles=np.concatenate(subT).flatten())

    fl = f.layout
    offset = 0
    nrowsOff = 0
    datg = []
    iio = 0
    iioo = 0
    layu = {}
    #print(firstrow)
    for j in range(firstrow):
        nbJ = dfCombGrG.loc[j]["s"]
        #print("firstRow",j,nbJ)
        datasJ = d[(offset * 2):(offset + nbJ) * 2]

        layoutJ = getLayoutsScene(l, offset, nbJ)
        dfCombGrCountJ = dfCombGrCount.loc[j]
        nbT = dfCombGrCountJ.values.ravel()
        #print(nbT)
        iiop = 0
        for i_, j2 in enumerate(nbT):
            nrows, ncols = dims[i_]
            iio2 = 0
            iio2X = 0
            #print(iiop,j2)
            layoutJ2 = layoutJ[iiop:(iiop + j2)]
            datasJ2 = datasJ[iiop * 2:(iiop + j2) * 2]
            if i_ == 0:
                lsr = list(fl.annotations)
                ooi2 = -0.1
                lop = "scene" + ("" if iio == 0 else str(iio + 1))
                ooi = fl[lop]["domain"]["y"][1]
                texto = "x : " + layoutJ2[0]["xaxis"]["title"]["text"]
                fl.annotations = lsr + [
                    dict(yref="paper",
                         showarrow=F,
                         x=ooi2,
                         y=ooi,
                         font=dict(size=16),
                         xref="paper",
                         text=texto,
                         yanchor="top",
                         xanchor="center",
                         textangle=0)
                ]
            #print("second",j2,nrows,ncols)
            for k in range(nrows):
                texto = "y : " + layoutJ2[k]["yaxis"]["title"]["text"]
                #lop="scene"+("" if iio==0 else str(iio+1))
                for k2 in range(ncols):
                    #print("IIO",iio+1)
                    lop = "scene" + ("" if iio == 0 else str(iio + 1))
                    lopX = "scene" + ("" if iio + i_ +
                                      j == 0 else str(iio + i_ + j + 1))
                    #print("t",k,k2,layoutJ2,iio2)
                    layU = copy(layoutJ2[iio2])
                    layU2 = fl[lopX]["domain"]
                    layU["domain"] = layU2
                    #print("lop",k,lop,lopX,layU2)
                    layU.camera.eye = dict(x=-1.5, y=1.5, z=-0.1)
                    layU["xaxis"]["title"]["text"] = "x"
                    layU["yaxis"]["title"]["text"] = "y"
                    layU["zaxis"]["title"]["text"] = "z"
                    layu[lopX] = layU.to_plotly_json()
                    datU = datasJ2[iio2X]
                    datU2 = datasJ2[iio2X + 1]

                    datU["scene"] = lopX
                    datU2["scene"] = lopX
                    datg.append(datU)
                    datg.append(datU2)
                    iio2 += 1
                    iiop += 1
                    iioo += 1
                    iio += 1
                    iio2X += 2
                    if iio2 == (j2):
                        iio += (nrows * nbCols - j2)
                        break
                lsr = list(fl.annotations)
                ooi2 = max(layU2["x"]) + 0.1
                ooi = fl[lop]["domain"]["y"][1]
                #texto="x : "+layoutJ2[k]["yaxis"]["title"]["text"]
                fl.annotations = lsr + [
                    dict(yref="paper",
                         showarrow=F,
                         x=ooi2,
                         y=ooi,
                         font=dict(size=16),
                         xref="paper",
                         text=texto,
                         yanchor="top",
                         xanchor="center",
                         textangle=0)
                ]
                nrowsOff += 1

        offset += nbJ
    layu["coloraxis"] = l["coloraxis"]
    #layu["coloraxis"]["colorbar"].titleside="right"
    layu["coloraxis"]["colorbar"]["x"] = 1.25
    layu["showlegend"] = False
    return go.Figure(data=datg, layout=merge(fl.to_plotly_json(), layu, add=F))