Esempio n. 1
0
 def test_update_dict(self):
     title = "this"
     fig = Figure()
     update_res1 = fig.update(layout=Layout(title=title))
     assert fig == Figure(layout=Layout(title=title))
     update_res2 = fig["layout"].update(xaxis=XAxis())
     assert fig == Figure(layout=Layout(title=title, xaxis=XAxis()))
     assert update_res1 is fig
     assert update_res2 is fig.layout
Esempio n. 2
0
 def test_update_list_empty(self):
     trace1 = Scatter(x=[1, 2, 3], y=[2, 1, 2])
     trace2 = Scatter(x=[1, 2, 3], y=[3, 2, 1])
     fig = Figure([trace1, trace2])
     fig.update([])
     d1, d2 = strip_dict_params(fig.data[0],
                                Scatter(x=[1, 2, 3], y=[2, 1, 2]))
     assert d1 == d2
     d1, d2 = strip_dict_params(fig.data[1],
                                Scatter(x=[1, 2, 3], y=[3, 2, 1]))
     assert d1 == d2
Esempio n. 3
0
def test_append_scatter():
    expected = Figure(
        data=Data([Scatter(x=[1, 2, 3], y=[2, 3, 4], xaxis="x5", yaxis="y5")]),
        layout=Layout(
            xaxis1=XAxis(domain=[0.0, 0.2888888888888889], anchor="y1"),
            xaxis2=XAxis(domain=[0.35555555555555557, 0.6444444444444445],
                         anchor="y2"),
            xaxis3=XAxis(domain=[0.7111111111111111, 1.0], anchor="y3"),
            xaxis4=XAxis(domain=[0.0, 0.2888888888888889], anchor="y4"),
            xaxis5=XAxis(domain=[0.35555555555555557, 0.6444444444444445],
                         anchor="y5"),
            xaxis6=XAxis(domain=[0.7111111111111111, 1.0], anchor="y6"),
            yaxis1=YAxis(domain=[0.575, 1.0], anchor="x1"),
            yaxis2=YAxis(domain=[0.575, 1.0], anchor="x2"),
            yaxis3=YAxis(domain=[0.575, 1.0], anchor="x3"),
            yaxis4=YAxis(domain=[0.0, 0.425], anchor="x4"),
            yaxis5=YAxis(domain=[0.0, 0.425], anchor="x5"),
            yaxis6=YAxis(domain=[0.0, 0.425], anchor="x6"),
        ),
    )

    trace = Scatter(x=[1, 2, 3], y=[2, 3, 4])
    fig = tls.make_subplots(rows=2, cols=3)
    fig.append_trace(trace, 2, 2)

    d1, d2 = strip_dict_params(fig["data"][0], expected["data"][0])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig["layout"], expected["layout"])
    assert d1 == d2
Esempio n. 4
0
	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
Esempio n. 5
0
    def test_update_list(self):
        trace1 = Scatter(x=[1, 2, 3], y=[2, 1, 2])
        trace2 = Scatter(x=[1, 2, 3], y=[3, 2, 1])
        fig = Figure([trace1, trace2])
        update = dict(x=[2, 3, 4], y=[1, 2, 3])
        update_res1 = fig.data[0].update(update)
        update_res2 = fig.data[1].update(update)

        d1, d2 = strip_dict_params(fig.data[0],
                                   Scatter(x=[2, 3, 4], y=[1, 2, 3]))
        assert d1 == d2
        d1, d2 = strip_dict_params(fig.data[1],
                                   Scatter(x=[2, 3, 4], y=[1, 2, 3]))
        assert d1 == d2
        assert update_res1 is fig.data[0]
        assert update_res2 is fig.data[1]
Esempio n. 6
0
    def test_figure_json_encoding(self):
        df = pd.DataFrame(columns=["col 1"], data=[1, 2, 3])
        s1 = Scatter3d(x=numeric_list, y=np_list, z=mixed_list)
        s2 = Scatter(x=df["col 1"])
        data = Data([s1, s2])
        figure = Figure(data=data)

        js1 = _json.dumps(s1, cls=utils.PlotlyJSONEncoder, sort_keys=True)
        js2 = _json.dumps(s2, cls=utils.PlotlyJSONEncoder, sort_keys=True)

        assert (
            js1 == '{"type": "scatter3d", "x": [1, 2, 3], '
            '"y": [1, 2, 3, null, null, null, "2014-01-05T00:00:00"], '
            '"z": [1, "A", "2014-01-05T00:00:00", '
            '"2014-01-05T01:01:01", "2014-01-05T01:01:01.000001"]}'
        )
        assert js2 == '{"type": "scatter", "x": [1, 2, 3]}'

        # Test JSON encoding works
        _json.dumps(data, cls=utils.PlotlyJSONEncoder, sort_keys=True)
        _json.dumps(figure, cls=utils.PlotlyJSONEncoder, sort_keys=True)

        # Test data wasn't mutated
        np_array = np.array([1, 2, 3, np.NaN, np.NAN, np.Inf, dt(2014, 1, 5)])
        for k in range(len(np_array)):
            if k in [3, 4]:
                # check NaN
                assert np.isnan(np_list[k]) and np.isnan(np_array[k])
            else:
                # non-NaN
                assert np_list[k] == np_array[k]

        assert set(data[0]["z"]) == set(
            [
                1,
                "A",
                dt(2014, 1, 5),
                dt(2014, 1, 5, 1, 1, 1),
                dt(2014, 1, 5, 1, 1, 1, 1),
            ]
        )
Esempio n. 7
0
def return_figure_from_figure_or_data(figure_or_data, validate_figure):
    from plotly_study.graph_objs import Figure
    from plotly_study.basedatatypes import BaseFigure

    validated = False
    if isinstance(figure_or_data, dict):
        figure = figure_or_data
    elif isinstance(figure_or_data, list):
        figure = {"data": figure_or_data}
    elif isinstance(figure_or_data, BaseFigure):
        figure = figure_or_data.to_dict()
        validated = True
    else:
        raise exceptions.PlotlyError(
            "The `figure_or_data` positional "
            "argument must be "
            "`dict`-like, `list`-like, or an instance of plotly_study.graph_objs.Figure"
        )

    if validate_figure and not validated:

        try:
            figure = Figure(**figure).to_dict()
        except exceptions.PlotlyError as err:
            raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "
                                         "Plotly will not be able to properly "
                                         "parse the resulting JSON. If you "
                                         "want to send this 'figure_or_data' "
                                         "to Plotly anyway (not recommended), "
                                         "you can set 'validate=False' as a "
                                         "plot option.\nHere's why you're "
                                         "seeing this error:\n\n{0}"
                                         "".format(err))
        if not figure["data"]:
            raise exceptions.PlotlyEmptyDataError(
                "Empty data list found. Make sure that you populated the "
                "list of data objects you're sending and try again.\n"
                "Questions? Visit support.plot.ly")

    return figure
Esempio n. 8
0
def test_append_scatter3d():
    expected = Figure(
        data=Data([
            Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene="scene1"),
            Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene="scene2"),
        ]),
        layout=Layout(
            scene1=Scene(domain={
                "y": [0.575, 1.0],
                "x": [0.0, 1.0]
            }),
            scene2=Scene(domain={
                "y": [0.0, 0.425],
                "x": [0.0, 1.0]
            }),
        ),
    )

    fig = tls.make_subplots(rows=2,
                            cols=1,
                            specs=[[{
                                "is_3d": True
                            }], [{
                                "is_3d": True
                            }]])
    trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3])
    fig.append_trace(trace, 1, 1)
    fig.append_trace(trace, 2, 1)

    d1, d2 = strip_dict_params(fig["data"][0], expected["data"][0])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig["data"][1], expected["data"][1])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig["layout"], expected["layout"])
    assert d1 == d2
Esempio n. 9
0
def test_append_trace_before_make_subplots():
    trace = Scatter(x=[1, 2, 3], y=[2, 3, 4])
    fig = Figure()
    fig.append_trace(trace, 2, 2)
Esempio n. 10
0
def test_print_grid_before_make_subplots():
    fig = Figure()
    fig.print_grid()
Esempio n. 11
0
def _set_axis(self,traces,on=None,side='right',title=''):
	"""
	Sets the axis in which each trace should appear
	If the axis doesn't exist then a new axis is created

	Parameters:
	-----------
		traces : list(str)
			List of trace names
		on : string
			The axis in which the traces should be placed.
			If this is not indicated then a new axis will be
			created
		side : string
			Side where the axis will be placed
				'left'
				'right'
		title : string
			Sets the title of the axis
			Applies only to new axis
	"""
	fig={}
	fig_cpy=fig_to_dict(self).copy()
	fig['data']=fig_cpy['data']
	fig['layout']=fig_cpy['layout']
	fig=Figure(fig)
	traces=make_list(traces)

	def update_data(trace,y):
		anchor=fig.axis['def'][y]['anchor'] if 'anchor' in fig.axis['def'][y] else 'x1'
		idx=fig.trace_dict[trace] if isinstance(trace,str) else trace
		fig['data'][idx]['xaxis']=anchor
		fig['data'][idx]['yaxis']=y

	for trace in traces:
		if on:
			if on not in fig.axis['def']:
				raise Exception('"on" axis does not exists: {0}'.format(on))
			update_data(trace,y=on)
		else:
			curr_x,curr_y=fig.axis['ref'][trace]
			domain='[0.0, 1.0]' if 'domain' not in fig.axis['def'][curr_y] else str(fig.axis['def'][curr_y]['domain'])
			try:
				new_axis=fig.axis['dom']['y'][domain][side]
			except KeyError:
				axis=fig.axis['def'][curr_y].copy()
				### check overlaying values
				axis.update(title=title,overlaying=curr_y,side=side,anchor=curr_x)
				axis_idx=str(fig.axis['len']['y']+1)
				fig['layout']['yaxis{0}'.format(axis_idx)]=axis
				new_axis='y{0}'.format(axis_idx)
			update_data(trace,y=new_axis)


	for k in list(fig.axis['def'].keys()):
		id='{0}axis{1}'.format(k[0],k[-1:])
		if k not in fig.axis['ref_axis']:
			try:
				del fig['layout'][id]
			except KeyError:
				pass

	return fig
Esempio n. 12
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))