diff --git a/pyproject.toml b/pyproject.toml index cbc0163..ece95e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ dependencies = [ ] [project.optional-dependencies] -dev = ["pytest", "packaging", "ruff==0.11.12"] +dev = ["pytest", "packaging", "pandas", "ruff==0.11.12"] [project.urls] Homepage = "https://github.com/plotly/matplotlylib" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..b758441 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,9 @@ +import matplotlib.pyplot as plt +import pytest + + +@pytest.fixture(autouse=True) +def close_figures(): + """Close all matplotlib figures after each test.""" + yield + plt.close("all") diff --git a/tests/test_annotations.py b/tests/test_annotations.py new file mode 100644 index 0000000..117fa42 --- /dev/null +++ b/tests/test_annotations.py @@ -0,0 +1,47 @@ +import matplotlib.pyplot as plt +import pytest + +from matplotlylib import mpl_to_plotly + + +def test_annotations(): + fig, ax = plt.subplots() + ax.plot([1, 2, 3], "b-") + ax.plot([3, 2, 1], "b-") + ax.text(0.001, 0.999, "top-left", transform=ax.transAxes, va="top", ha="left") + ax.text( + 0.001, 0.001, "bottom-left", transform=ax.transAxes, va="baseline", ha="left" + ) + ax.text(0.999, 0.999, "top-right", transform=ax.transAxes, va="top", ha="right") + ax.text( + 0.999, 0.001, "bottom-right", transform=ax.transAxes, va="baseline", ha="right" + ) + + plotly_fig = mpl_to_plotly(fig) + + annotations = {a.text: a for a in plotly_fig.layout.annotations} + assert sorted(annotations) == [ + "bottom-left", + "bottom-right", + "top-left", + "top-right", + ] + expected = { + "top-left": (0.001, 0.999, "left", "top"), + "bottom-left": (0.001, 0.001, "left", "bottom"), + "top-right": (0.999, 0.999, "right", "top"), + "bottom-right": (0.999, 0.001, "right", "bottom"), + } + for text, (x, y, xanchor, yanchor) in expected.items(): + annotation = annotations[text] + assert annotation.xref == "paper" + assert annotation.yref == "paper" + assert annotation.showarrow is False + assert annotation.xanchor == xanchor + assert annotation.yanchor == yanchor + assert annotation.align == xanchor + # The plotly plot area is not exactly the size of the matplotlib axes + # (497 vs 496 pixels wide here), so paper coordinates can be off by a + # pixel or two + assert annotation.x == pytest.approx(x, abs=0.005) + assert annotation.y == pytest.approx(y, abs=0.005) diff --git a/tests/test_axis_scales.py b/tests/test_axis_scales.py new file mode 100644 index 0000000..ed69d95 --- /dev/null +++ b/tests/test_axis_scales.py @@ -0,0 +1,29 @@ +import matplotlib.pyplot as plt +import pytest + +from matplotlylib import mpl_to_plotly + + +def test_even_linear_scale(): + fig, ax = plt.subplots() + ax.plot([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 3, 100, 6, 45, 4, 80, 45, 3, 59]) + # Minor ticks beyond the data widen the view limits + ax.set_xticks(list(range(0, 20, 3)), minor=True) + ax.set_yticks(list(range(0, 200, 13)), minor=True) + + plotly_fig = mpl_to_plotly(fig) + + xaxis, yaxis = plotly_fig.layout.xaxis, plotly_fig.layout.yaxis + assert xaxis.type == "linear" + assert yaxis.type == "linear" + assert list(xaxis.range) == pytest.approx([0, 18]) + assert list(yaxis.range) == pytest.approx([-1.85, 195]) + # The major ticks come from matplotlib's automatic locator, so plotly gets + # their number (10 on each axis over the widened limits) rather than + # explicit tick values + assert xaxis.nticks == 10 + assert yaxis.nticks == 10 + assert xaxis.tickvals is None + assert yaxis.tickvals is None + assert xaxis.dtick is None + assert yaxis.dtick is None diff --git a/tests/test_bars.py b/tests/test_bars.py new file mode 100644 index 0000000..eb67a09 --- /dev/null +++ b/tests/test_bars.py @@ -0,0 +1,80 @@ +import matplotlib.pyplot as plt +import pytest + +from matplotlylib import mpl_to_plotly + + +def test_vertical_bar(): + fig, ax = plt.subplots() + ax.bar(x=[0, 1, 2, 3, 4, 5], height=[10, 20, 50, 80, 100, 200]) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 1 + bar = plotly_fig.data[0] + assert bar.type == "bar" + assert bar.orientation == "v" + assert list(bar.x) == [0, 1, 2, 3, 4, 5] + assert list(bar.y) == [10, 20, 50, 80, 100, 200] + assert bar.marker.color == "#1F77B4" + assert bar.opacity == 1 + # Default bar width 0.8 at spacing 1 + assert plotly_fig.layout.bargap == pytest.approx(0.2) + + +def test_horizontal_bar(): + fig, ax = plt.subplots() + ax.barh(y=[0, 1, 2, 3, 4, 5, 6], width=[1, 4, 8, 16, 32, 64, 128]) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 1 + bar = plotly_fig.data[0] + assert bar.type == "bar" + assert bar.orientation == "h" + assert list(bar.x) == [1, 4, 8, 16, 32, 64, 128] + assert list(bar.y) == [0, 1, 2, 3, 4, 5, 6] + assert bar.marker.color == "#1F77B4" + assert bar.opacity == 1 + # Default bar height 0.8 at spacing 1 + assert plotly_fig.layout.bargap == pytest.approx(0.2) + + +def test_h_and_v_bars(): + fig, ax = plt.subplots() + ax.bar( + x=[0, 10, 20, 30, 40, 50], + height=[1, 4, 8, 16, 32, 64], + width=10, + color="green", + alpha=0.5, + ) + ax.barh( + y=[15, 30, 45, 60, 75, 90], + width=[30, 60, 20, 50, 60, 30], + height=14, + color="red", + alpha=0.5, + ) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 2 + vertical, horizontal = plotly_fig.data + assert vertical.type == "bar" + assert vertical.orientation == "v" + assert list(vertical.x) == [0, 10, 20, 30, 40, 50] + assert list(vertical.y) == [1, 4, 8, 16, 32, 64] + assert vertical.marker.color == "rgba(0, 128, 0, 0.5)" + assert vertical.opacity == 0.5 + + assert horizontal.type == "bar" + assert horizontal.orientation == "h" + assert list(horizontal.x) == [30, 60, 20, 50, 60, 30] + assert list(horizontal.y) == [15, 30, 45, 60, 75, 90] + assert horizontal.marker.color == "rgba(255, 0, 0, 0.5)" + assert horizontal.opacity == 0.5 + + # Plotly has one bargap per figure, and the bars drawn last set it: the + # horizontal bars are 14 high at spacing 15, a gap of 1/15 + assert plotly_fig.layout.bargap == pytest.approx(1 / 15) diff --git a/tests/test_data.py b/tests/test_data.py new file mode 100644 index 0000000..0b98cf1 --- /dev/null +++ b/tests/test_data.py @@ -0,0 +1,60 @@ +import matplotlib.pyplot as plt + +from matplotlylib import mpl_to_plotly + +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] + + +def test_line_data(): + fig, ax = plt.subplots() + ax.plot(X1, Y1) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 1 + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 + + +def test_lines_data(): + fig, ax = plt.subplots() + ax.plot(X1, Y1) + ax.plot(X2, Y2) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 2 + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 + assert list(plotly_fig.data[1].x) == X2 + assert list(plotly_fig.data[1].y) == Y2 + + +def test_bar_data(): + fig, ax = plt.subplots() + ax.bar(X1, Y1) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 1 + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 + + +def test_bars_data(): + fig, ax = plt.subplots() + ax.bar(X1, Y1, color="r") + ax.barh(X2, Y2, color="b") + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 2 + # Vertical bars: positions on x, heights on y + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 + # Horizontal bars: widths on x, positions on y + assert list(plotly_fig.data[1].x) == Y2 + assert list(plotly_fig.data[1].y) == X2 diff --git a/tests/test_date_times.py b/tests/test_date_times.py new file mode 100644 index 0000000..4cbec40 --- /dev/null +++ b/tests/test_date_times.py @@ -0,0 +1,53 @@ +import datetime + +import matplotlib.pyplot as plt +import pandas as pd +import pytest +from matplotlib.dates import date2num + +from matplotlylib import mpl_to_plotly + + +def test_normal_mpl_dates(): + date_strings = [ + "2010-01-04 00:00:00", + "2010-01-04 10:00:00", + "2010-01-04 23:00:59", + "2010-01-05 00:00:00", + ] + dates = [datetime.datetime.fromisoformat(s) for s in date_strings] + + # Plot matplotlib date numbers on a date axis, as plot_date used to + fig, ax = plt.subplots() + ax.xaxis_date() + ax.plot(date2num(dates), [1, 2, 3, 4], "o") + + plotly_fig = mpl_to_plotly(fig) + + assert plotly_fig.layout.xaxis.type == "date" + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert trace.mode == "markers" + assert list(trace.x) == date_strings + assert list(trace.y) == [1, 2, 3, 4] + + +@pytest.mark.xfail( + strict=True, + reason="pandas time series plots keep matplotlib's day numbers as x values " + "on a date axis, so plotly reads them as milliseconds since 1970", +) +def test_pandas_time_series_date_formatter(): + df = pd.DataFrame( + {"a": [0, 1, 2], "Date": pd.date_range("2001-01-01", periods=3, freq="D")} + ) + fig = df.plot(x="Date").figure + + plotly_fig = mpl_to_plotly(fig) + + assert plotly_fig.layout.xaxis.type == "date" + assert list(plotly_fig.data[0].x) == [ + "2001-01-01 00:00:00", + "2001-01-02 00:00:00", + "2001-01-03 00:00:00", + ] diff --git a/tests/test_lines.py b/tests/test_lines.py new file mode 100644 index 0000000..e81f384 --- /dev/null +++ b/tests/test_lines.py @@ -0,0 +1,74 @@ +import matplotlib.pyplot as plt + +from matplotlylib import mpl_to_plotly + +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] + + +def test_simple_line(): + fig, ax = plt.subplots() + ax.plot(X1, Y1, label="simple") + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert trace.type == "scatter" + assert trace.mode == "lines" + assert trace.name == "simple" + assert list(trace.x) == X1 + assert list(trace.y) == Y1 + assert trace.line.color == "rgba(31, 119, 180, 1)" + assert trace.line.dash == "solid" + assert trace.line.width == 1.5 + + +def test_complicated_line(): + fig, ax = plt.subplots() + ax.plot(X1, Y1, "ro", markersize=10, alpha=0.5, label="one") + ax.plot(X1, Y1, "-b", linewidth=2, alpha=0.7, label="two") + ax.plot(X2, Y2, "b+", markeredgewidth=2, markersize=10, alpha=0.6, label="three") + ax.plot(X2, Y2, "--r", linewidth=2, alpha=0.8, label="four") + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 4 + red_circles, blue_line, blue_crosses, red_dashes = plotly_fig.data + + assert red_circles.mode == "markers" + assert red_circles.name == "one" + assert list(red_circles.x) == X1 + assert list(red_circles.y) == Y1 + assert red_circles.marker.symbol == "circle" + assert red_circles.marker.size == 10 + assert red_circles.marker.color == "#FF0000" + assert red_circles.marker.opacity == 0.5 + + assert blue_line.mode == "lines" + assert blue_line.name == "two" + assert list(blue_line.x) == X1 + assert list(blue_line.y) == Y1 + assert blue_line.line.color == "rgba(0, 0, 255, 0.7)" + assert blue_line.line.dash == "solid" + assert blue_line.line.width == 2 + + assert blue_crosses.mode == "markers" + assert blue_crosses.name == "three" + assert list(blue_crosses.x) == X2 + assert list(blue_crosses.y) == Y2 + assert blue_crosses.marker.symbol == "cross" + assert blue_crosses.marker.size == 10 + assert blue_crosses.marker.color == "#0000FF" + assert blue_crosses.marker.opacity == 0.6 + assert blue_crosses.marker.line.width == 2 + + assert red_dashes.mode == "lines" + assert red_dashes.name == "four" + assert list(red_dashes.x) == X2 + assert list(red_dashes.y) == Y2 + assert red_dashes.line.color == "rgba(255, 0, 0, 0.8)" + assert red_dashes.line.dash == "dash" + assert red_dashes.line.width == 2 diff --git a/tests/test_scatter.py b/tests/test_scatter.py new file mode 100644 index 0000000..657e821 --- /dev/null +++ b/tests/test_scatter.py @@ -0,0 +1,50 @@ +import matplotlib.pyplot as plt + +from matplotlylib import mpl_to_plotly + +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] + + +def test_simple_scatter(): + fig, ax = plt.subplots() + ax.scatter(X1, Y1) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert trace.type == "scatter" + assert trace.mode == "markers" + assert list(trace.x) == X1 + assert list(trace.y) == Y1 + assert trace.marker.symbol == "circle" + # matplotlib's s is the marker area in points^2, 36 by default + assert trace.marker.size == 6 + assert trace.marker.color == "rgba(31,119,180,1.0)" + + +def test_double_scatter(): + fig, ax = plt.subplots() + ax.scatter(X1, Y1, color="red", s=121, marker="^", alpha=0.5) + ax.scatter(X2, Y2, color="purple", s=64, marker="s", alpha=0.5) + + plotly_fig = mpl_to_plotly(fig) + + assert len(plotly_fig.data) == 2 + triangles, squares = plotly_fig.data + assert triangles.mode == "markers" + assert list(triangles.x) == X1 + assert list(triangles.y) == Y1 + assert triangles.marker.symbol == "triangle-up" + assert triangles.marker.size == 11 + assert triangles.marker.color == "rgba(255,0,0,0.5)" + + assert squares.mode == "markers" + assert list(squares.x) == X2 + assert list(squares.y) == Y2 + assert squares.marker.symbol == "square" + assert squares.marker.size == 8 + assert squares.marker.color == "rgba(128,0,128,0.5)" diff --git a/tests/test_subplots.py b/tests/test_subplots.py new file mode 100644 index 0000000..837aac0 --- /dev/null +++ b/tests/test_subplots.py @@ -0,0 +1,72 @@ +import matplotlib.pyplot as plt +import pytest +from matplotlib.gridspec import GridSpec + +from matplotlylib import mpl_to_plotly + +# The axes below fill columns 1-5 and rows 0-3 of a 4x6 GridSpec whose gaps +# are 0.6 of a cell. Plotly's paper spans just those cells, so it is +# 5 cells + 4 gaps = 7.4 cells wide and 4 cells + 3 gaps = 5.8 cells high. +CELL_AND_GAP = 1.6 +PAPER_WIDTH = 7.4 +PAPER_HEIGHT = 5.8 + + +def x_domain(first_col, last_col): + start = (first_col - 1) * CELL_AND_GAP + end = (last_col - 1) * CELL_AND_GAP + 1 + return [start / PAPER_WIDTH, end / PAPER_WIDTH] + + +def y_domain(first_row, last_row): + # Rows count from the top, plotly's domains from the bottom + top = first_row * CELL_AND_GAP + bottom = last_row * CELL_AND_GAP + 1 + return [1 - bottom / PAPER_HEIGHT, 1 - top / PAPER_HEIGHT] + + +def test_blank_subplots(): + fig = plt.figure() + gs = GridSpec(4, 6) + ax1 = fig.add_subplot(gs[0, 1]) + ax1.plot([0, 1], [1, 2]) + fig.add_subplot(gs[1, 1]) + fig.add_subplot(gs[2:, 1]) + fig.add_subplot(gs[0, 2:]) + fig.add_subplot(gs[1:3, 2:4]) + fig.add_subplot(gs[3, 2:5]) + fig.add_subplot(gs[1:3, 4:]) + fig.add_subplot(gs[3, 5]) + gs.update(hspace=0.6, wspace=0.6) + + plotly_fig = mpl_to_plotly(fig) + + # (first column, last column, first row, last row) of each subplot + cells = [ + (1, 1, 0, 0), + (1, 1, 1, 1), + (1, 1, 2, 3), + (2, 5, 0, 0), + (2, 3, 1, 2), + (2, 4, 3, 3), + (4, 5, 1, 2), + (5, 5, 3, 3), + ] + layout_keys = plotly_fig.layout.to_plotly_json() + assert len([k for k in layout_keys if k.startswith("xaxis")]) == len(cells) + assert len([k for k in layout_keys if k.startswith("yaxis")]) == len(cells) + for n, (first_col, last_col, first_row, last_row) in enumerate(cells, start=1): + xaxis = plotly_fig.layout[f"xaxis{n}"] + yaxis = plotly_fig.layout[f"yaxis{n}"] + assert list(xaxis.domain) == pytest.approx(x_domain(first_col, last_col)) + assert list(yaxis.domain) == pytest.approx(y_domain(first_row, last_row)) + suffix = "" if n == 1 else str(n) + assert xaxis.anchor == f"y{suffix}" + assert yaxis.anchor == f"x{suffix}" + + # The only line is on the first subplot + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert (trace.xaxis, trace.yaxis) == ("x", "y") + assert list(trace.x) == [0, 1] + assert list(trace.y) == [1, 2]