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)
Beispiel #2
0
    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()
Beispiel #4
0
    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}}},
            ],
        )
Beispiel #5
0
 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"
         }})],
     )
Beispiel #6
0
    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_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 fig1():
    pio.templates.default = None
    yield go.Figure(
        data=[
            go.Bar(y=[2, 1, 4],
                   marker=go.bar.Marker(color="purple", opacity=0.7)),
            go.Scattergl(y=[3, 4, 2]),
        ],
        layout={
            "font": {
                "family": "Arial",
                "size": 12
            },
            "xaxis": {
                "showticklabels": False
            },
            "yaxis": {
                "showticklabels": False
            },
            "showlegend": False,
        },
    )
    pio.templates.default = "plotly"
    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")],
            },
        )
Beispiel #10
0
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
Beispiel #11
0
    def draw_bar(self, coll):
        """Draw a collection of similar patches as a bar chart.

        After bars are sorted, an appropriate data dictionary must be created
        to tell plotly about this data. Just like draw_line or draw_markers,
        draw_bar translates patch/path information into something plotly
        understands.

        Positional arguments:
        patch_coll -- a collection of patches to be drawn as a bar chart.

        """
        tol = 1e-10
        trace = [mpltools.make_bar(**bar_props) for bar_props in coll]
        widths = [bar_props["x1"] - bar_props["x0"] for bar_props in trace]
        heights = [bar_props["y1"] - bar_props["y0"] for bar_props in trace]
        vertical = abs(
            sum(widths[0] - widths[iii] for iii in range(len(widths)))) < tol
        horizontal = (abs(
            sum(heights[0] - heights[iii]
                for iii in range(len(heights)))) < tol)
        if vertical and horizontal:
            # Check for monotonic x. Can't both be true!
            x_zeros = [bar_props["x0"] for bar_props in trace]
            if all((x_zeros[iii + 1] > x_zeros[iii]
                    for iii in range(len(x_zeros[:-1])))):
                orientation = "v"
            else:
                orientation = "h"
        elif vertical:
            orientation = "v"
        else:
            orientation = "h"
        if orientation == "v":
            self.msg += "    Attempting to draw a vertical bar chart\n"
            old_heights = [bar_props["y1"] for bar_props in trace]
            for bar in trace:
                bar["y0"], bar["y1"] = 0, bar["y1"] - bar["y0"]
            new_heights = [bar_props["y1"] for bar_props in trace]
            # check if we're stacked or not...
            for old, new in zip(old_heights, new_heights):
                if abs(old - new) > tol:
                    self.plotly_fig["layout"]["barmode"] = "stack"
                    self.plotly_fig["layout"]["hovermode"] = "x"
            x = [bar["x0"] + (bar["x1"] - bar["x0"]) / 2 for bar in trace]
            y = [bar["y1"] for bar in trace]
            bar_gap = mpltools.get_bar_gap([bar["x0"] for bar in trace],
                                           [bar["x1"] for bar in trace])
            if self.x_is_mpl_date:
                x = [bar["x0"] for bar in trace]
                formatter = (self.current_mpl_ax.get_xaxis().
                             get_major_formatter().__class__.__name__)
                x = mpltools.mpl_dates_to_datestrings(x, formatter)
        else:
            self.msg += "    Attempting to draw a horizontal bar chart\n"
            old_rights = [bar_props["x1"] for bar_props in trace]
            for bar in trace:
                bar["x0"], bar["x1"] = 0, bar["x1"] - bar["x0"]
            new_rights = [bar_props["x1"] for bar_props in trace]
            # check if we're stacked or not...
            for old, new in zip(old_rights, new_rights):
                if abs(old - new) > tol:
                    self.plotly_fig["layout"]["barmode"] = "stack"
                    self.plotly_fig["layout"]["hovermode"] = "y"
            x = [bar["x1"] for bar in trace]
            y = [bar["y0"] + (bar["y1"] - bar["y0"]) / 2 for bar in trace]
            bar_gap = mpltools.get_bar_gap([bar["y0"] for bar in trace],
                                           [bar["y1"] for bar in trace])
        bar = go.Bar(
            orientation=orientation,
            x=x,
            y=y,
            xaxis="x{0}".format(self.axis_ct),
            yaxis="y{0}".format(self.axis_ct),
            opacity=trace[0]["alpha"],  # TODO: get all alphas if array?
            marker=go.bar.Marker(
                color=trace[0]["facecolor"],  # TODO: get all
                line=dict(width=trace[0]["edgewidth"]),
            ),
        )  # TODO ditto
        if len(bar["x"]) > 1:
            self.msg += "    Heck yeah, I drew that bar chart\n"
            self.plotly_fig.add_trace(bar),
            if bar_gap is not None:
                self.plotly_fig["layout"]["bargap"] = np.round(bar_gap, 10)
        else:
            self.msg += "    Bar chart not drawn\n"
            warnings.warn("found box chart data with length <= 1, "
                          "assuming data redundancy, not plotting.")
Beispiel #12
0
    height=[10, 20, 50, 80, 100, 200],
    bottom=[0, 1, 2, 3, 4, 5, 6],
    width=[1, 4, 8, 16, 32, 64, 128],
    multi_left=[0, 10, 20, 30, 40, 50],
    multi_height=[1, 4, 8, 16, 32, 64],
    multi_bottom=[15, 30, 45, 60, 75, 90],
    multi_width=[30, 60, 20, 50, 60, 30],
)

VERTICAL_BAR = go.Figure(
    data=[
        go.Bar(
            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],
            orientation="v",
            marker=go.bar.Marker(line=dict(width=1.0), color="#1F77B4"),
            opacity=1,
            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,
        bargap=0.2,
        xaxis1=go.layout.XAxis(
            domain=[0.0, 1.0],