예제 #1
0
def test_wide_mode_internal_bar_exception(orientation):
    df_in = pd.DataFrame(dict(a=["q", "r", "s"], b=["t", "u", "v"]),
                         index=[11, 12, 13])
    args_in = dict(data_frame=df_in, color=None, orientation=orientation)
    args_out = build_dataframe(args_in, go.Bar)
    df_out = args_out.pop("data_frame")
    assert_frame_equal(
        df_out.sort_index(axis=1),
        pd.DataFrame(
            dict(
                index=[11, 12, 13, 11, 12, 13],
                variable=["a", "a", "a", "b", "b", "b"],
                value=["q", "r", "s", "t", "u", "v"],
                count=[1, 1, 1, 1, 1, 1],
            )).sort_index(axis=1),
    )
    if orientation is None or orientation == "v":
        assert args_out == dict(x="value",
                                y="count",
                                color="variable",
                                orientation="v")
    else:
        assert args_out == dict(x="count",
                                y="value",
                                color="variable",
                                orientation="h")
예제 #2
0
def test_non_matching_index():
    df = pd.DataFrame(dict(y=[1, 2, 3]), index=["a", "b", "c"])

    expected = pd.DataFrame(dict(x=["a", "b", "c"], y=[1, 2, 3]))

    args = dict(data_frame=df, x=df.index, y="y")
    out = build_dataframe(args, all_attrables, array_attrables)
    assert_frame_equal(expected, out["data_frame"])

    args = dict(data_frame=None, x=df.index, y=df.y)
    out = build_dataframe(args, all_attrables, array_attrables)
    assert_frame_equal(expected, out["data_frame"])

    args = dict(data_frame=None, x=["a", "b", "c"], y=df.y)
    out = build_dataframe(args, all_attrables, array_attrables)
    assert_frame_equal(expected, out["data_frame"])
예제 #3
0
def test_wide_mode_internal(trace_type, x, y, color, orientation):
    df_in = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6]), index=[11, 12, 13])
    args_in = dict(data_frame=df_in, color=None, orientation=orientation)
    args_out = build_dataframe(args_in, trace_type)
    df_out = args_out.pop("data_frame")
    expected = dict(
        variable=["a", "a", "a", "b", "b", "b"],
        value=[1, 2, 3, 4, 5, 6],
    )
    if x == "index":
        expected["index"] = [11, 12, 13, 11, 12, 13]
    assert_frame_equal(
        df_out.sort_index(axis=1),
        pd.DataFrame(expected).sort_index(axis=1),
    )
    if trace_type in [go.Histogram2dContour, go.Histogram2d]:
        if orientation is None or orientation == "v":
            assert args_out == dict(x=x, y=y, color=color)
        else:
            assert args_out == dict(x=y, y=x, color=color)
    else:
        if (orientation is None
                and trace_type != go.Funnel) or orientation == "v":
            assert args_out == dict(x=x, y=y, color=color, orientation="v")
        else:
            assert args_out == dict(x=y, y=x, color=color, orientation="h")
예제 #4
0
def test_wide_mode_internal_special_cases(df_in, args_in, args_expect, df_expect):
    args_in["data_frame"] = df_in
    args_out = build_dataframe(args_in, go.Scatter)
    df_out = args_out.pop("data_frame")
    assert args_out == args_expect
    assert_frame_equal(
        df_out.sort_index(axis=1), df_expect.sort_index(axis=1),
    )
예제 #5
0
def test_build_df_from_lists():
    # Just lists
    args = dict(x=[1, 2, 3], y=[2, 3, 4], color=[1, 3, 9])
    output = {key: key for key in args}
    df = pd.DataFrame(args)
    args["data_frame"] = None
    out = build_dataframe(args, go.Scatter)
    assert_frame_equal(df.sort_index(axis=1), out["data_frame"].sort_index(axis=1))
    out.pop("data_frame")
    assert out == output

    # Arrays
    args = dict(x=np.array([1, 2, 3]), y=np.array([2, 3, 4]), color=[1, 3, 9])
    output = {key: key for key in args}
    df = pd.DataFrame(args)
    args["data_frame"] = None
    out = build_dataframe(args, go.Scatter)
    assert_frame_equal(df.sort_index(axis=1), out["data_frame"].sort_index(axis=1))
    out.pop("data_frame")
    assert out == output
예제 #6
0
def test_wide_x_or_y(tt, df_in, args_in, x, y, color, df_out_exp, transpose):
    if transpose:
        args_in["y"], args_in["x"] = args_in["x"], args_in["y"]
    args_in["data_frame"] = df_in
    args_out = build_dataframe(args_in, tt)
    df_out = args_out.pop("data_frame").sort_index(axis=1)
    assert_frame_equal(df_out, pd.DataFrame(df_out_exp).sort_index(axis=1))
    if transpose:
        args_exp = dict(x=y, y=x, color=color)
    else:
        args_exp = dict(x=x, y=y, color=color)
    if tt not in [go.Histogram2dContour, go.Histogram2d]:
        orientation_exp = args_in["orientation"]
        if (args_in["x"] is None) != (args_in["y"] is None) and tt != go.Histogram:
            orientation_exp = "h" if transpose else "v"
        args_exp["orientation"] = orientation_exp
    assert args_out == args_exp
예제 #7
0
def test_timezones():
    df = pd.DataFrame({"date": ["2015-04-04 19:31:30+1:00"], "value": [3]})
    df["date"] = pd.to_datetime(df["date"])
    args = dict(data_frame=df, x="date", y="value")
    out = build_dataframe(args, go.Scatter)
    assert str(out["data_frame"]["date"][0]) == str(df["date"][0])
예제 #8
0
def test_build_df_with_index():
    tips = px.data.tips()
    args = dict(data_frame=tips, x=tips.index, y="total_bill")
    out = build_dataframe(args, go.Scatter)
    assert_frame_equal(tips.reset_index()[out["data_frame"].columns],
                       out["data_frame"])
예제 #9
0
def create_hexbin_mapbox(
    data_frame=None,
    lat=None,
    lon=None,
    color=None,
    nx_hexagon=5,
    agg_func=None,
    animation_frame=None,
    color_discrete_sequence=None,
    color_discrete_map={},
    labels={},
    color_continuous_scale=None,
    range_color=None,
    color_continuous_midpoint=None,
    opacity=None,
    zoom=None,
    center=None,
    mapbox_style=None,
    title=None,
    template=None,
    width=None,
    height=None,
    min_count=None,
    show_original_data=False,
    original_data_marker=None,
):
    """
    Returns a figure aggregating scattered points into connected hexagons
    """
    args = build_dataframe(args=locals(), constructor=None)

    if agg_func is None:
        agg_func = np.mean

    lat_range = args["data_frame"][args["lat"]].agg(["min", "max"]).values
    lon_range = args["data_frame"][args["lon"]].agg(["min", "max"]).values

    hexagons_lats, hexagons_lons, hexagons_ids, count = _compute_wgs84_hexbin(
        lat=args["data_frame"][args["lat"]].values,
        lon=args["data_frame"][args["lon"]].values,
        lat_range=lat_range,
        lon_range=lon_range,
        color=None,
        nx=nx_hexagon,
        agg_func=agg_func,
        min_count=min_count,
    )

    geojson = _hexagons_to_geojson(hexagons_lats, hexagons_lons, hexagons_ids)

    if zoom is None:
        if height is None and width is None:
            mapDim = dict(height=450, width=450)
        elif height is None and width is not None:
            mapDim = dict(height=450, width=width)
        elif height is not None and width is None:
            mapDim = dict(height=height, width=height)
        else:
            mapDim = dict(height=height, width=width)
        zoom = _getBoundsZoomLevel(lon_range[0], lon_range[1], lat_range[0],
                                   lat_range[1], mapDim)

    if center is None:
        center = dict(lat=lat_range.mean(), lon=lon_range.mean())

    if args["animation_frame"] is not None:
        groups = args["data_frame"].groupby(args["animation_frame"]).groups
    else:
        groups = {0: args["data_frame"].index}

    agg_data_frame_list = []
    for frame, index in groups.items():
        df = args["data_frame"].loc[index]
        _, _, hexagons_ids, aggregated_value = _compute_wgs84_hexbin(
            lat=df[args["lat"]].values,
            lon=df[args["lon"]].values,
            lat_range=lat_range,
            lon_range=lon_range,
            color=df[args["color"]].values if args["color"] else None,
            nx=nx_hexagon,
            agg_func=agg_func,
            min_count=min_count,
        )
        agg_data_frame_list.append(
            pd.DataFrame(np.c_[hexagons_ids, aggregated_value],
                         columns=["locations", "color"]))
    agg_data_frame = (pd.concat(
        agg_data_frame_list, axis=0,
        keys=groups.keys()).rename_axis(index=("frame",
                                               "index")).reset_index("frame"))

    agg_data_frame["color"] = pd.to_numeric(agg_data_frame["color"])

    if range_color is None:
        range_color = [
            agg_data_frame["color"].min(), agg_data_frame["color"].max()
        ]

    fig = choropleth_mapbox(
        data_frame=agg_data_frame,
        geojson=geojson,
        locations="locations",
        color="color",
        hover_data={
            "color": True,
            "locations": False,
            "frame": False
        },
        animation_frame=("frame"
                         if args["animation_frame"] is not None else None),
        color_discrete_sequence=color_discrete_sequence,
        color_discrete_map=color_discrete_map,
        labels=labels,
        color_continuous_scale=color_continuous_scale,
        range_color=range_color,
        color_continuous_midpoint=color_continuous_midpoint,
        opacity=opacity,
        zoom=zoom,
        center=center,
        mapbox_style=mapbox_style,
        title=title,
        template=template,
        width=width,
        height=height,
    )

    if show_original_data:
        original_fig = scatter_mapbox(
            data_frame=(args["data_frame"].sort_values(
                by=args["animation_frame"]) if args["animation_frame"]
                        is not None else args["data_frame"]),
            lat=args["lat"],
            lon=args["lon"],
            animation_frame=args["animation_frame"],
        )
        original_fig.data[0].hoverinfo = "skip"
        original_fig.data[0].hovertemplate = None
        original_fig.data[0].marker = original_data_marker

        fig.add_trace(original_fig.data[0])

        if args["animation_frame"] is not None:
            for i in range(len(original_fig.frames)):
                original_fig.frames[i].data[0].hoverinfo = "skip"
                original_fig.frames[i].data[0].hovertemplate = None
                original_fig.frames[i].data[0].marker = original_data_marker

                fig.frames[i].data = [
                    fig.frames[i].data[0],
                    original_fig.frames[i].data[0],
                ]

    return fig