def test_move_nested_trace_properties(self): fig = go.Figure( data=[ go.Bar(y=[1, 2, 3], marker={ "opacity": 0.6, "color": "green" }), go.Scatter(x=[1, 3, 2], marker={ "size": 30, "color": [1, 1, 0] }), go.Bar(y=[3, 2, 1], marker={ "opacity": 0.4, "color": [1, 0.5, 0] }), ], layout={"barmode": "group"}, ) templated_fig = pio.to_templated(fig) expected_fig = go.Figure( data=[ go.Bar(y=[1, 2, 3]), go.Scatter(x=[1, 3, 2], marker={"color": [1, 1, 0]}), go.Bar(y=[3, 2, 1], marker={"color": [1, 0.5, 0]}), ], layout={ "template": { "data": { "scatter": [go.Scatter(marker={"size": 30})], "bar": [ go.Bar(marker={ "opacity": 0.6, "color": "green" }), go.Bar(marker={"opacity": 0.4}), ], }, "layout": { "barmode": "group" }, } }, ) self.assertEqual(pio.to_json(templated_fig), pio.to_json(expected_fig))
def test_update_data_empty(self): # Create figure with empty data (no traces) figure = go.Figure(layout={"width": 1000}) # Update data with new traces figure.update(data=[go.Scatter(y=[2, 1, 3]), go.Bar(y=[1, 2, 3])]) # Build expected dict expected = { "data": [ { "y": [2, 1, 3], "type": "scatter" }, { "y": [1, 2, 3], "type": "bar" }, ], "layout": { "width": 1000 }, } # Compute expected figure dict (pop uids for comparison) result = figure.to_dict() # Perform comparison self.assertEqual(result, expected)
def setUp(self): # Construct initial scatter object self.scatter = go.Scatter(name="scatter A") # Assert initial state d1, d2 = strip_dict_params( self.scatter, {"type": "scatter", "name": "scatter A"} ) assert d1 == d2 # Construct expected results self.expected_toplevel = { "type": "scatter", "name": "scatter A", "fillcolor": "green", } self.expected_nested = { "type": "scatter", "name": "scatter A", "marker": {"colorbar": {"title": {"font": {"family": "courier"}}}}, } self.expected_nested_error_x = { "type": "scatter", "name": "scatter A", "error_x": {"type": "percent"}, }
def test_trace_repr(self): N = 100 scatt = go.Scatter( y=list(range(N)), marker={ "color": "green", "opacity": [e / N for e in range(N)] }, ) expected = """\ Scatter({ 'marker': {'color': 'green', 'opacity': [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99]}, 'y': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] })""" self.assertEqual(scatt.__repr__(), expected)
def test_bug_1462(self): # https: // github.com / plotly / plotly_study.py / issues / 1462 fig = go.Figure( data=[ go.Scatter(x=[1, 2], y=[1, 2], xaxis="x"), go.Scatter(x=[2, 3], y=[2, 3], xaxis="x2"), ] ) layout_dict = { "grid": {"xaxes": ["x", "x2"], "yaxes": ["y"]}, "xaxis2": {"matches": "x", "title": {"text": "total_bill"}}, } fig.update(layout=layout_dict) updated_layout_dict = fig.layout.to_plotly_json() self.assertEqual(updated_layout_dict, layout_dict)
def latexfig(): pio.templates.default = None trace1 = go.Scatter(x=[1, 2, 3, 4], y=[1, 4, 9, 16]) trace2 = go.Scatter(x=[1, 2, 3, 4], y=[0.5, 2, 4.5, 8]) data = [trace1, trace2] layout = go.Layout( xaxis=dict(title="$\\sqrt{(n_\\text{c}(t|{T_\\text{early}}))}$", showticklabels=False), yaxis=dict(title="$d, r \\text{ (solar radius)}$", showticklabels=False), showlegend=False, font={ "family": "Arial", "size": 12 }, ) fig = go.Figure(data=data, layout=layout) yield fig pio.templates.default = "plotly"
def setUp(self): # Construct with mocked _send_restyle_msg method self.figure = go.Figure(data=[ go.Scatter(), go.Bar(), go.Parcoords(dimensions=[{}, { "label": "dim 2" }, {}]), ]) # Mock out the message method self.figure._send_restyle_msg = MagicMock()
def setUp(self): # Construct initial scatter object self.figure = go.Figure( data=[ go.Scatter(y=[3, 2, 1], marker={"color": "green"}), go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}), go.Sankey(arrangement="snap"), ] ) # Mock out the message methods self.figure._send_moveTraces_msg = MagicMock() self.figure._send_deleteTraces_msg = MagicMock()
def test_update_traces_overwrite(self): fig = go.Figure( data=[go.Scatter(marker_line_color="red"), go.Bar(marker_line_color="red")] ) fig.update_traces(overwrite=True, marker={"line": {"width": 10}}) self.assertEqual( fig.to_plotly_json()["data"], [ {"type": "scatter", "marker": {"line": {"width": 10}}}, {"type": "bar", "marker": {"line": {"width": 10}}}, ], )
def setUp(self): # Disable default template pio.templates.default = None # Construct initial scatter object self.figure = go.Figure( data=[go.Scatter(y=[3, 2, 1], marker={"color": "green"})], layout={"xaxis": { "range": [-1, 4] }}, frames=[go.Frame(layout={"yaxis": { "title": "f1" }})], )
def test_attr_access(self): scatt_uid = self.figure.data[0].uid self.assertEqual( self.figure.data, (go.Scatter(y=[3, 2, 1], marker={"color": "green"}, uid=scatt_uid), ), ) self.assertEqual(self.figure.layout, go.Layout(xaxis={"range": [-1, 4]})) self.assertEqual(self.figure.frames, (go.Frame(layout={"yaxis": { "title": "f1" }}), ))
def setUp(self): # Construct initial scatter object self.figure = go.Figure( data=[ go.Scatter(y=[3, 2, 1], marker={"color": "green"}), go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}), ], layout={ "xaxis": { "range": [-1, 4] }, "width": 1000 }, frames=[go.Frame(layout={"yaxis": { "title": "f1" }})], )
def setUp(self): # Construct initial scatter object self.figure = go.Figure( data=[ go.Scatter(y=[3, 2, 1], marker={"color": "green"}), go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}), ], layout={"xaxis": { "range": [-1, 4] }}, frames=[go.Frame(layout={"yaxis": { "title": "f1" }})], ) # Mock out the message method self.figure._send_animate_msg = MagicMock()
def test_trace_repr_elided(self): N = 1000 scatt = go.Scatter( y=list(range(N)), marker={ "color": "green", "opacity": [e / N for e in range(N)] }, ) expected = """\ Scatter({ 'marker': {'color': 'green', 'opacity': [0.0, 0.001, 0.002, ..., 0.997, 0.998, 0.999]}, 'y': [0, 1, 2, ..., 997, 998, 999] })""" self.assertEqual(scatt.__repr__(), expected)
def test_toplevel(self): # Initialize scatter scatter = go.Scatter( name="scatter A", y=[3, 2, 4], marker={"colorbar": {"title": {"font": {"family": "courier"}}}}, ) expected = { "type": "scatter", "name": "scatter A", "y": [3, 2, 4], "marker": {"colorbar": {"title": {"font": {"family": "courier"}}}}, } d1, d2 = strip_dict_params(scatter, expected) assert d1 == d2 # Set property not defined to None scatter.x = None d1, d2 = strip_dict_params(scatter, expected) assert d1 == d2 scatter["line.width"] = None d1, d2 = strip_dict_params(scatter, expected) assert d1 == d2 # Set defined property to None scatter.y = None expected.pop("y") d1, d2 = strip_dict_params(scatter, expected) assert d1 == d2 # Set compound properties to None scatter[("marker", "colorbar", "title", "font")] = None expected["marker"]["colorbar"]["title"].pop("font") d1, d2 = strip_dict_params(scatter, expected) assert d1 == d2 scatter.marker = None expected.pop("marker") d1, d2 = strip_dict_params(scatter, expected) assert d1 == d2
def setUp(self): # Construct initial scatter object self.scatter = go.Scatter(name="scatter A") # Assert initial state d1, d2 = strip_dict_params( self.scatter, {"type": "scatter", "name": "scatter A"} ) assert d1 == d2 # Construct expected results self.expected_toplevel = { "type": "scatter", "name": "scatter A", "marker": {"color": "yellow", "size": 10}, } self.expected_nested = { "type": "scatter", "name": "scatter A", "marker": {"colorbar": {"bgcolor": "yellow", "thickness": 5}}, }
def execute_plotly_example(): """ Some typical code which would go inside a gallery example. """ import plotly_study.graph_objs as go # Create random data with numpy import numpy as np N = 200 random_x = np.random.randn(N) random_y_0 = np.random.randn(N) random_y_1 = np.random.randn(N) - 1 # Create traces trace_0 = go.Scatter(x=random_x, y=random_y_0, mode="markers", name="Above") fig = go.Figure(data=[trace_0]) plotly_study.io.show(fig)
def test_validate_assigned_traces_are_subset(self): traces = self.figure.data self.figure.data = [traces[2], go.Scatter(y=[3, 2, 1]), traces[1]]
def test_invalid_constructor_kwarg(self): go.Scatter(bogus=87)
D = dict( x1=[0, 1, 2, 3, 4, 5], y1=[10, 20, 50, 80, 100, 200], x2=[0, 1, 2, 3, 4, 5, 6], y2=[1, 4, 8, 16, 32, 64, 128], ) SIMPLE_LINE = go.Figure( data=[ go.Scatter( x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], name="simple", mode="lines", line=go.scatter.Line(dash="solid", color="rgba (31, 119, 180, 1)", width=1.5), xaxis="x1", yaxis="y1", ) ], layout=go.Layout( width=640, height=480, autosize=False, margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), hovermode="closest", showlegend=False, xaxis1=go.layout.XAxis( domain=[0.0, 1.0],
D = dict( x1=[1, 2, 2, 4, 5, 6, 1, 7, 8, 5, 3], y1=[5, 3, 7, 2, 9, 7, 8, 4, 5, 9, 2], x2=[-1, 1, -0.3, -0.6, 0.4, 0.8, -0.1, 0.7], y2=[-0.5, 0.4, 0.7, -0.6, 0.3, -1, 0, 0.3], ) SIMPLE_SCATTER = go.Figure( data=[ go.Scatter( x=[1.0, 2.0, 2.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 5.0, 3.0], y=[5.0, 3.0, 7.0, 2.0, 9.0, 7.0, 8.0, 4.0, 5.0, 9.0, 2.0], mode="markers", marker=go.scatter.Marker( symbol="circle", line=dict(color="rgba(31,119,180,1.0)", width=1.0), size=6.0, color="rgba(31,119,180,1.0)", ), xaxis="x1", yaxis="y1", ) ], layout=go.Layout( width=640, height=480, autosize=False, margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), hovermode="closest", showlegend=False, xaxis1=go.layout.XAxis(
def draw_marked_line(self, **props): """Create a data dict for a line obj. This will draw 'lines', 'markers', or 'lines+markers'. props.keys() -- [ 'coordinates', ('data', 'axes', 'figure', or 'display') 'data', (a list of xy pairs) 'mplobj', (the matplotlib.lines.Line2D obj being rendered) 'label', (the name of the Line2D obj being rendered) 'linestyle', (linestyle dict, can be None, see below) 'markerstyle', (markerstyle dict, can be None, see below) ] props['linestyle'].keys() -- [ 'alpha', (opacity of Line2D obj) 'color', (color of the line if it exists, not the marker) 'linewidth', 'dasharray', (code for linestyle, see DASH_MAP in mpltools.py) 'zorder', (viewing precedence when stacked with other objects) ] props['markerstyle'].keys() -- [ 'alpha', (opacity of Line2D obj) 'marker', (the mpl marker symbol, see SYMBOL_MAP in mpltools.py) 'facecolor', (color of the marker face) 'edgecolor', (color of the marker edge) 'edgewidth', (width of marker edge) 'markerpath', (an SVG path for drawing the specified marker) 'zorder', (viewing precedence when stacked with other objects) ] """ self.msg += " Attempting to draw a line " line, marker = {}, {} if props["linestyle"] and props["markerstyle"]: self.msg += "... with both lines+markers\n" mode = "lines+markers" elif props["linestyle"]: self.msg += "... with just lines\n" mode = "lines" elif props["markerstyle"]: self.msg += "... with just markers\n" mode = "markers" if props["linestyle"]: color = mpltools.merge_color_and_opacity( props["linestyle"]["color"], props["linestyle"]["alpha"]) # print(mpltools.convert_dash(props['linestyle']['dasharray'])) line = go.scatter.Line( color=color, width=props["linestyle"]["linewidth"], dash=mpltools.convert_dash(props["linestyle"]["dasharray"]), ) if props["markerstyle"]: marker = go.scatter.Marker( opacity=props["markerstyle"]["alpha"], color=props["markerstyle"]["facecolor"], symbol=mpltools.convert_symbol(props["markerstyle"]["marker"]), size=props["markerstyle"]["markersize"], line=dict( color=props["markerstyle"]["edgecolor"], width=props["markerstyle"]["edgewidth"], ), ) if props["coordinates"] == "data": marked_line = go.Scatter( mode=mode, name=(str(props["label"]) if isinstance( props["label"], six.string_types) else props["label"]), x=[xy_pair[0] for xy_pair in props["data"]], y=[xy_pair[1] for xy_pair in props["data"]], xaxis="x{0}".format(self.axis_ct), yaxis="y{0}".format(self.axis_ct), line=line, marker=marker, ) if self.x_is_mpl_date: formatter = (self.current_mpl_ax.get_xaxis(). get_major_formatter().__class__.__name__) marked_line["x"] = mpltools.mpl_dates_to_datestrings( marked_line["x"], formatter) self.plotly_fig.add_trace(marked_line), self.msg += " Heck yeah, I drew that line\n" else: self.msg += " Line didn't have 'data' coordinates, " "not drawing\n" warnings.warn("Bummer! Plotly can currently only draw Line2D " "objects from matplotlib that are in 'data' " "coordinates!")
from __future__ import absolute_import import plotly_study.graph_objs as go D = dict(x1=[0, 1], y1=[1, 2]) BLANK_SUBPLOTS = go.Figure( data=[ go.Scatter( x=[0.0, 1.0], y=[1.0, 2.0], name="_line0", mode="lines", line=go.scatter.Line(dash="solid", color="#0000FF", width=1.0), xaxis="x1", yaxis="y1", ) ], layout=go.Layout( width=640, height=480, autosize=False, margin=go.layout.Margin(l=168, r=63, b=52, t=57, pad=0), hovermode="closest", showlegend=False, xaxis1=go.layout.XAxis( domain=[0.0, 0.13513513513513517], range=[-0.050000000000000003, 1.05], type="linear", showline=True, ticks="inside",
def setUp(self): # Construct initial scatter object self.scatter = go.Scatter() self.scatter.name = "Scatter 1"
from __future__ import absolute_import import plotly_study.graph_objs as go ANNOTATIONS = go.Figure( data=[ go.Scatter( x=[0.0, 1.0, 2.0], y=[1.0, 2.0, 3.0], name="_line0", mode="lines", line=go.scatter.Line(dash="solid", color="rgba (0, 0, 255, 1)", width=1.5), xaxis="x1", yaxis="y1", ), go.Scatter( x=[0.0, 1.0, 2.0], y=[3.0, 2.0, 1.0], name="_line1", mode="lines", line=go.scatter.Line(dash="solid", color="rgba (0, 0, 255, 1)", width=1.5), xaxis="x1", yaxis="y1", ), ], layout=go.Layout( width=640,
def setUp(self): self.template1 = go.layout.Template( layout={"font": { "size": 20, "family": "Rockwell" }}, data={ "scatter": [ go.Scatter(line={"dash": "solid"}), go.Scatter(line={"dash": "dot"}), ], "bar": [ go.Bar(marker={"opacity": 0.7}), go.Bar(marker={"opacity": 0.4}), ], "parcoords": [go.Parcoords(dimensiondefaults={"multiselect": True})] # no 'scattergl' }, ) pio.templates["template1"] = self.template1 self.template1_orig = copy.deepcopy(self.template1) self.template2 = go.layout.Template( layout={ "paper_bgcolor": "green", "font": { "size": 14, "color": "yellow" } }, data={ "scatter": [ go.Scatter(marker={"color": "red"}), go.Scatter(marker={"color": "green"}), go.Scatter(marker={"color": "blue"}), ], # no 'bar' "parcoords": [ go.Parcoords(line={"colorscale": "Viridis"}), go.Parcoords(line={"colorscale": "Blues"}), ], "scattergl": [go.Scattergl(hoverinfo="x+y")], }, ) pio.templates["template2"] = self.template2 self.template2_orig = copy.deepcopy(self.template2) self.expected1_2 = go.layout.Template( layout={ "paper_bgcolor": "green", "font": { "size": 14, "color": "yellow", "family": "Rockwell" }, }, data={ "scatter": [ go.Scatter(marker={"color": "red"}, line={"dash": "solid"}), go.Scatter(marker={"color": "green"}, line={"dash": "dot"}), go.Scatter(marker={"color": "blue"}, line={"dash": "solid"}), go.Scatter(marker={"color": "red"}, line={"dash": "dot"}), go.Scatter(marker={"color": "green"}, line={"dash": "solid"}), go.Scatter(marker={"color": "blue"}, line={"dash": "dot"}), ], "bar": [ go.Bar(marker={"opacity": 0.7}), go.Bar(marker={"opacity": 0.4}), ], "parcoords": [ go.Parcoords( dimensiondefaults={"multiselect": True}, line={"colorscale": "Viridis"}, ), go.Parcoords( dimensiondefaults={"multiselect": True}, line={"colorscale": "Blues"}, ), ], "scattergl": [go.Scattergl(hoverinfo="x+y")], }, )
def test_raise_if_no_figure(self): scatt = go.Scatter() fn = MagicMock() scatt.on_change(fn, "x")
def _bullet( df, markers, measures, ranges, subtitles, titles, orientation, range_colors, measure_colors, horizontal_spacing, vertical_spacing, scatter_options, layout_options, ): num_of_lanes = len(df) num_of_rows = num_of_lanes if orientation == "h" else 1 num_of_cols = 1 if orientation == "h" else num_of_lanes if not horizontal_spacing: horizontal_spacing = 1.0 / num_of_lanes if not vertical_spacing: vertical_spacing = 1.0 / num_of_lanes fig = plotly_study.tools.make_subplots( num_of_rows, num_of_cols, print_grid=False, horizontal_spacing=horizontal_spacing, vertical_spacing=vertical_spacing, ) # layout fig["layout"].update( dict(shapes=[]), title="Bullet Chart", height=600, width=1000, showlegend=False, barmode="stack", annotations=[], margin=dict(l=120 if orientation == "h" else 80), ) # update layout fig["layout"].update(layout_options) if orientation == "h": width_axis = "yaxis" length_axis = "xaxis" else: width_axis = "xaxis" length_axis = "yaxis" for key in fig["layout"]: if "xaxis" in key or "yaxis" in key: fig["layout"][key]["showgrid"] = False fig["layout"][key]["zeroline"] = False if length_axis in key: fig["layout"][key]["tickwidth"] = 1 if width_axis in key: fig["layout"][key]["showticklabels"] = False fig["layout"][key]["range"] = [0, 1] # narrow domain if 1 bar if num_of_lanes <= 1: fig["layout"][width_axis + "1"]["domain"] = [0.4, 0.6] if not range_colors: range_colors = ["rgb(200, 200, 200)", "rgb(245, 245, 245)"] if not measure_colors: measure_colors = ["rgb(31, 119, 180)", "rgb(176, 196, 221)"] for row in range(num_of_lanes): # ranges bars for idx in range(len(df.iloc[row]["ranges"])): inter_colors = clrs.n_colors(range_colors[0], range_colors[1], len(df.iloc[row]["ranges"]), "rgb") x = ([sorted(df.iloc[row]["ranges"])[-1 - idx]] if orientation == "h" else [0]) y = ([0] if orientation == "h" else [sorted(df.iloc[row]["ranges"])[-1 - idx]]) bar = go.Bar( x=x, y=y, marker=dict(color=inter_colors[-1 - idx]), name="ranges", hoverinfo="x" if orientation == "h" else "y", orientation=orientation, width=2, base=0, xaxis="x{}".format(row + 1), yaxis="y{}".format(row + 1), ) fig.add_trace(bar) # measures bars for idx in range(len(df.iloc[row]["measures"])): inter_colors = clrs.n_colors( measure_colors[0], measure_colors[1], len(df.iloc[row]["measures"]), "rgb", ) x = ([sorted(df.iloc[row]["measures"])[-1 - idx]] if orientation == "h" else [0.5]) y = ([0.5] if orientation == "h" else [sorted(df.iloc[row]["measures"])[-1 - idx]]) bar = go.Bar( x=x, y=y, marker=dict(color=inter_colors[-1 - idx]), name="measures", hoverinfo="x" if orientation == "h" else "y", orientation=orientation, width=0.4, base=0, xaxis="x{}".format(row + 1), yaxis="y{}".format(row + 1), ) fig.add_trace(bar) # markers x = df.iloc[row]["markers"] if orientation == "h" else [0.5] y = [0.5] if orientation == "h" else df.iloc[row]["markers"] markers = go.Scatter(x=x, y=y, name="markers", hoverinfo="x" if orientation == "h" else "y", xaxis="x{}".format(row + 1), yaxis="y{}".format(row + 1), **scatter_options) fig.add_trace(markers) # titles and subtitles title = df.iloc[row]["titles"] if "subtitles" in df: subtitle = "<br>{}".format(df.iloc[row]["subtitles"]) else: subtitle = "" label = "<b>{}</b>".format(title) + subtitle annot = utils.annotation_dict_for_label( label, (num_of_lanes - row if orientation == "h" else row + 1), num_of_lanes, vertical_spacing if orientation == "h" else horizontal_spacing, "row" if orientation == "h" else "col", True if orientation == "h" else False, False, ) fig["layout"]["annotations"] += (annot, ) return fig