ronantakizawa/codereview-bench huggingface dataset:
Repository: matplotlib/matplotlib
File: lib/mpl_toolkits/mplot3d/art3d.py (Python)

Code before:
# art3d.py, original mplot3d version by John Porter
# Parts rewritten by Reinier Heeres <reinier@heeres.eu>
# Minor additions by Ben Axelrod <baxelrod@coroware.com>

"""
Module containing 3D artist code and functions to convert 2D
artists into 3D versions which can be added to an Axes3D.
"""

import math
import warnings

import numpy as np

from contextlib import contextmanager

from matplotlib import (
    _api, artist, cbook, colors as mcolors, lines, text as mtext,
    path as mpath, rcParams)
from matplotlib.collections import (
    Collection, LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.patches import Patch
from . import proj3d


def _norm_angle(a):
    """Return the given angle normalized to -180 < *a* <= 180 degrees."""
    a = (a + 360) % 360
    if a > 180:
        a = a - 360
    return a


def _norm_text_angle(a):
    """Return the given angle normalized to -90 < *a* <= 90 degrees."""
    a = (a + 180) % 180

Review comment (suggestion):
Remove the unused import, then this PR lgtm.

The linked issue should be kept open after this is merged.

Code after:
# art3d.py, original mplot3d version by John Porter
# Parts rewritten by Reinier Heeres <reinier@heeres.eu>
# Minor additions by Ben Axelrod <baxelrod@coroware.com>

"""
Module containing 3D artist code and functions to convert 2D
artists into 3D versions which can be added to an Axes3D.
"""

import math

import numpy as np

from contextlib import contextmanager

from matplotlib import (
    _api, artist, cbook, colors as mcolors, lines, text as mtext,
    path as mpath, rcParams)
from matplotlib.collections import (
    Collection, LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.patches import Patch
from . import proj3d


def _norm_angle(a):
    """Return the given angle normalized to -180 < *a* <= 180 degrees."""
    a = (a + 360) % 360
    if a > 180:
        a = a - 360
    return a


def _norm_text_angle(a):
    """Return the given angle normalized to -90 < *a* <= 90 degrees."""
    a = (a + 180) % 180
    if a > 90:
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_backend_macosx.py (Python)

Code before:
    with mock.patch(prop, return_value="foobar.png"):
        fname = fig.canvas.manager.toolbar.save_figure()
        os.remove("foobar.png")
        assert fname == "foobar.png"
    with mock.patch(prop, return_value=None):
        fname = fig.canvas.manager.toolbar.save_figure()
        assert fname is None


@pytest.mark.backend('macosx', skip_on_importerror=True)
def test_save_figure_return():
    subprocess_run_helper(_test_save_figure_return, timeout=_test_timeout,
                          extra_env={"MPLBACKEND": "macosx"})


@pytest.mark.backend('macosx', skip_on_importerror=True)
def test_create_figure_on_worker_thread_fails():

    def create_figure():
        warn_msg = "Matplotlib GUI outside of the main thread will likely fail."
        err_msg = "Cannot create a GUI FigureManager outside the main thread"
        with pytest.warns(UserWarning, match=warn_msg):
            with pytest.raises(RuntimeError, match=err_msg):
                plt.gcf()

    worker = threading.Thread(target=create_figure)
    worker.start()
    worker.join()


Review comment (bug):
This test should probably go in a subprocess (like a few others in this file) or else if broken, it would break the whole test suite.

Code after:
    with mock.patch(prop, return_value="foobar.png"):
        fname = fig.canvas.manager.toolbar.save_figure()
        os.remove("foobar.png")
        assert fname == "foobar.png"
    with mock.patch(prop, return_value=None):
        fname = fig.canvas.manager.toolbar.save_figure()
        assert fname is None


@pytest.mark.backend('macosx', skip_on_importerror=True)
def test_save_figure_return():
    subprocess_run_helper(_test_save_figure_return, timeout=_test_timeout,
                          extra_env={"MPLBACKEND": "macosx"})


def _test_create_figure_on_worker_thread_fails():
    def create_figure():
        warn_msg = "Matplotlib GUI outside of the main thread will likely fail."
        err_msg = "Cannot create a GUI FigureManager outside the main thread"
        with pytest.warns(UserWarning, match=warn_msg):
            with pytest.raises(RuntimeError, match=err_msg):
                plt.gcf()

    worker = threading.Thread(target=create_figure)
    worker.start()
    worker.join()


@pytest.mark.backend('macosx', skip_on_importerror=True)
def test_create_figure_on_worker_thread_fails():
    subprocess_run_helper(
        _test_create_figure_on_worker_thread_fails,
        timeout=_test_timeout,
        extra_env={"MPLBACKEND": "macosx"}
    )
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_legend.py (Python)

Code before:

    # Check that there's a legend handle
    handles = leg.legend_handles
    assert len(handles) == 1
    assert isinstance(handles[0], mpatches.Rectangle)

    plt.close(fig)


def test_patchcollection_legend_properties():
    # Test that PatchCollection legend preserves visual properties
    fig, ax = plt.subplots()

    # Create patches with specific properties
    p1 = mpatches.Circle((0, 0), 1)
    p2 = mpatches.Circle((2, 0), 1)

    # Create a PatchCollection with specific visual properties
    pc = mcollections.PatchCollection(
        [p1, p2],
        label="styled patches",
        facecolor='red',
        edgecolor='blue',
        linewidths=3,
        linestyle='--'
    )
    ax.add_collection(pc)
    ax.autoscale_view()

    # Create the legend
    leg = ax.legend()
    legend_patch = leg.legend_handles[0]

    # Verify that visual properties are preserved
    assert_allclose(legend_patch.get_facecolor()[:3],
                    pc.get_facecolor()[0][:3], rtol=1e-5)
    assert_allclose(legend_patch.get_edgecolor()[:3],
                    pc.get_edgecolor()[0][:3], rtol=1e-5)
    assert legend_patch.get_linewidth() == pc.get_linewidths()[0]
    assert legend_patch.get_linestyle() == pc.get_linestyles()[0]

    plt.close(fig)


def test_patchcollection_legend_match_original():
    # Test PatchCollection legend with match_original=True
    fig, ax = plt.subplots()

    # Create patches with individual colors
    p1 = mpatches.Rectangle((0, 0), 1, 1, facecolor='red', edgecolor='black')
    p2 = mpatches.Rectangle((2, 0), 1, 1, facecolor='green', edgecolor='blue')

Review comment (suggestion):
also more compact:
```suggestion
    pc = mcollections.PatchCollection(
        [mpatches.Circle((0, 0), 1), mpatches.Circle((2, 0), 1)],
        label="styled patches",
        facecolor='red',
        edgecolor='blue',
        linewidths=3,
        linestyle='--',
    )
```

Code after:
    assert leg.get_texts()[0].get_text() == "patch collection"

    # Check that the legend handle exists and has correct visual properties
    assert len(leg.legend_handles) == 1
    legend_patch = leg.legend_handles[0]
    assert mpl.colors.same_color(legend_patch.get_facecolor(),
                                  pc.get_facecolor()[0])
    assert mpl.colors.same_color(legend_patch.get_edgecolor(),
                                  pc.get_edgecolor()[0])
    assert legend_patch.get_linewidth() == pc.get_linewidths()[0]
    assert legend_patch.get_linestyle() == pc.get_linestyles()[0]


def test_patchcollection_legend_empty():
    # Test that empty PatchCollection doesn't crash
    fig, ax = plt.subplots()

    # Create an empty PatchCollection
    pc = mcollections.PatchCollection([], label="empty collection")
    ax.add_collection(pc)

    # This should not crash
    leg = ax.legend()

    # Check that the label still appears
    assert len(leg.get_texts()) == 1
    assert leg.get_texts()[0].get_text() == "empty collection"

    # The legend handle should exist
    assert len(leg.legend_handles) == 1
Repository: matplotlib/matplotlib
File: galleries/examples/widgets/radio_buttons_grid.py (Python)

Code before:
from matplotlib.widgets import RadioButtons

# Generate sample data
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

fig, (ax_plot, ax_buttons) = plt.subplots(
    1,
    2,
    figsize=(8, 4),
    width_ratios=[4, 1.4],
)

# Create initial plot
(line,) = ax_plot.plot(t, s, lw=2, color="red")
ax_plot.set_xlabel("Time (s)")
ax_plot.set_ylabel("Amplitude")
ax_plot.set_title("Sine Wave - Click a color!")
ax_plot.grid(True, alpha=0.3)

# Configure the radio buttons axes
ax_buttons.set_facecolor("lightgray")
ax_buttons.set_title("Line Color", fontsize=12, pad=10)
# Create a 2D grid of color options (3 rows x 2 columns)
colors = ["red", "yellow", "green", "purple", "brown", "gray"]
radio = RadioButtons(ax_buttons, colors, active=0, layout=(3, 2))


def color_func(label):
    """Update the line color based on selected button."""
    line.set_color(label)
    fig.canvas.draw()


radio.on_clicked(color_func)

plt.show()

# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.widgets.RadioButtons`


Review comment (suggestion):
```suggestion
radio = RadioButtons(ax_buttons, colors, layout=(3, 2))
```

Code after:
from matplotlib.widgets import RadioButtons

# Generate sample data
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

fig, (ax_plot, ax_buttons) = plt.subplots(
    1,
    2,
    figsize=(8, 4),
    width_ratios=[4, 1.4],
)

# Create initial plot
(line,) = ax_plot.plot(t, s, lw=2, color="red")
ax_plot.set_xlabel("Time (s)")
ax_plot.set_ylabel("Amplitude")
ax_plot.set_title("Sine Wave - Click a color!")
ax_plot.grid(True, alpha=0.3)

# Configure the radio buttons axes
ax_buttons.set_facecolor("0.9")
ax_buttons.set_title("Line Color", fontsize=12, pad=10)
# Create a 2D grid of color options (3 rows x 2 columns)
colors = ["red", "yellow", "green", "purple", "brown", "gray"]
radio = RadioButtons(ax_buttons, colors, layout=(3, 2))


def color_func(label):
    """Update the line color based on selected button."""
    line.set_color(label)
    fig.canvas.draw()


radio.on_clicked(color_func)

plt.show()

# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.widgets.RadioButtons`
#
# .. tags::
#
#    styling: color
#    styling: conditional
Repository: matplotlib/matplotlib
File: galleries/examples/widgets/radio_buttons_grid.py (Python)

Code before:
(line,) = ax_plot.plot(t, s, lw=2, color="red")
ax_plot.set_xlabel("Time (s)")
ax_plot.set_ylabel("Amplitude")
ax_plot.set_title("Sine Wave - Click a color!")
ax_plot.grid(True, alpha=0.3)

# Configure the radio buttons axes
ax_buttons.set_facecolor("0.9")
ax_buttons.set_title("Line Color", fontsize=12, pad=10)
# Create a 2D grid of color options (3 rows x 2 columns)
colors = ["red", "yellow", "green", "purple", "brown", "gray"]
radio = RadioButtons(ax_buttons, colors, layout=(3, 2))


def color_func(label):
    """Update the line color based on selected button."""
    line.set_color(label)
    fig.canvas.draw()


radio.on_clicked(color_func)

plt.show()

# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.widgets.RadioButtons`


Review comment (suggestion):
would you mind adding tags like `styling:color` to this? 

https://matplotlib.org/devdocs/devel/tag_guidelines.html

Code after:
(line,) = ax_plot.plot(t, s, lw=2, color="red")
ax_plot.set_xlabel("Time (s)")
ax_plot.set_ylabel("Amplitude")
ax_plot.set_title("Sine Wave - Click a color!")
ax_plot.grid(True, alpha=0.3)

# Configure the radio buttons axes
ax_buttons.set_facecolor("0.9")
ax_buttons.set_title("Line Color", fontsize=12, pad=10)
# Create a 2D grid of color options (3 rows x 2 columns)
colors = ["red", "yellow", "green", "purple", "brown", "gray"]
radio = RadioButtons(ax_buttons, colors, layout=(3, 2))


def color_func(label):
    """Update the line color based on selected button."""
    line.set_color(label)
    fig.canvas.draw()


radio.on_clicked(color_func)

plt.show()

# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.widgets.RadioButtons`
#
# .. tags::
#
#    styling: color
#    styling: conditional
#    plot-type: line
#    level: intermediate
#    purpose: showcase
Repository: matplotlib/matplotlib
File: galleries/examples/color/color_sequences.py (Python)

Code before:

import matplotlib as mpl


def plot_color_sequences(names, ax):
    # Display each named color sequence horizontally on the supplied axes.

    for n, name in enumerate(names):
        colors = mpl.color_sequences[name]
        n_colors = len(colors)
        x = np.arange(n_colors)
        y = np.full_like(x, n)

        ax.scatter(x, y, facecolor=colors, edgecolor='dimgray', s=200, zorder=2)

    ax.set_yticks(range(len(names)), labels=names)
    ax.grid(visible=True, axis='y')
    ax.yaxis.set_inverted(True)
    ax.xaxis.set_visible(False)
    ax.spines[:].set_visible(False)
    ax.tick_params(left=False)


built_in_color_sequences = [
    'tab10', 'tab20', 'tab20b', 'tab20c', 'Pastel1', 'Pastel2', 'Paired',
    'Accent', 'Accessible', 'Dark2', 'Set1', 'Set2', 'Set3', 'petroff6',
    'petroff8', 'petroff10']


fig, ax = plt.subplots(figsize=(6.4, 9.6), layout='constrained')

plot_color_sequences(built_in_color_sequences, ax)
ax.set_title('Built In Color Sequences')

plt.show()


# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.colors.ColorSequenceRegistry`
#    - `matplotlib.axes.Axes.scatter`
#
# .. tags::
#
#    styling: color
#    purpose: reference

Review comment (suggestion):
```suggestion
    'Accent', 'okabe-ito', 'Dark2', 'Set1', 'Set2', 'Set3', 'petroff6',
```

Many of these sequences are accessible on different dimensions. Users should choose the pallet that fulfills their constraints, rather than MPL declaring any one sequence the "accessible" one.  

Code after:

import matplotlib as mpl


def plot_color_sequences(names, ax):
    # Display each named color sequence horizontally on the supplied axes.

    for n, name in enumerate(names):
        colors = mpl.color_sequences[name]
        n_colors = len(colors)
        x = np.arange(n_colors)
        y = np.full_like(x, n)

        ax.scatter(x, y, facecolor=colors, edgecolor='dimgray', s=200, zorder=2)

    ax.set_yticks(range(len(names)), labels=names)
    ax.grid(visible=True, axis='y')
    ax.yaxis.set_inverted(True)
    ax.xaxis.set_visible(False)
    ax.spines[:].set_visible(False)
    ax.tick_params(left=False)


built_in_color_sequences = [
    'tab10', 'tab20', 'tab20b', 'tab20c', 'Pastel1', 'Pastel2', 'Paired',
    'Accent', 'okabe_ito', 'Dark2', 'Set1', 'Set2', 'Set3', 'petroff6',
    'petroff8', 'petroff10']


fig, ax = plt.subplots(figsize=(6.4, 9.6), layout='constrained')

plot_color_sequences(built_in_color_sequences, ax)
ax.set_title('Built In Color Sequences')

plt.show()


# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.colors.ColorSequenceRegistry`
#    - `matplotlib.axes.Axes.scatter`
#
# .. tags::
#
#    styling: color
#    purpose: reference
Repository: matplotlib/matplotlib
File: lib/matplotlib/transforms.py (Python)

Code before:


def _interval_contains_open(interval, val):
    """
    Check, excluding endpoints, whether an interval includes a given value.

    Parameters
    ----------
    interval : (float, float)
        The endpoints of the interval.
    val : float
        Value to check is within interval.

    Returns
    -------
    bool
        Whether *val* is within the *interval*.
    """
    a, b = interval
    return a < val < b or a > val > b


@_api.deprecated("3.11")
def interval_contains_open(interval, val):
    return _interval_contains_open(interval, val)
_interval_contains_open.__doc__ = _interval_contains_open.__doc__


def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'):
    """
    Return a new transform with an added offset.

    Parameters
    ----------
    trans : `Transform` subclass
        Any transform, to which offset will be applied.
    fig : `~matplotlib.figure.Figure`, default: None
        Current figure. It can be None if *units* are 'dots'.
    x, y : float, default: 0.0
        The offset to apply.
    units : {'inches', 'points', 'dots'}, default: 'inches'
        Units of the offset.

    Returns
    -------
    `Transform` subclass
        Transform with applied offset.
    """
    _api.check_in_list(['dots', 'points', 'inches'], units=units)
    if units == 'dots':
        return trans + Affine2D().translate(x, y)

Review comment (suggestion):
```suggestion
interval_contains_open.__doc__ = _interval_contains_open.__doc__
```
But this clobbers the deprecation note.

Code after:


def _interval_contains_open(interval, val):
    """
    Check, excluding endpoints, whether an interval includes a given value.

    Parameters
    ----------
    interval : (float, float)
        The endpoints of the interval.
    val : float
        Value to check is within interval.

    Returns
    -------
    bool
        Whether *val* is within the *interval*.
    """
    a, b = interval
    return a < val < b or a > val > b


@_api.deprecated("3.11")
@_docstring.copy(_interval_contains_open)
def interval_contains_open(interval, val):
    return _interval_contains_open(interval, val)


def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'):
    """
    Return a new transform with an added offset.

    Parameters
    ----------
    trans : `Transform` subclass
        Any transform, to which offset will be applied.
    fig : `~matplotlib.figure.Figure`, default: None
        Current figure. It can be None if *units* are 'dots'.
    x, y : float, default: 0.0
        The offset to apply.
    units : {'inches', 'points', 'dots'}, default: 'inches'
        Units of the offset.

    Returns
    -------
    `Transform` subclass
        Transform with applied offset.
    """
    _api.check_in_list(['dots', 'points', 'inches'], units=units)
    if units == 'dots':
        return trans + Affine2D().translate(x, y)
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_axes.py (Python)

Code before:
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z[:-1, :-1])
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z[:-1, :-1])
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30)


@check_figures_equal()
def test_pcolor_log_scale(fig_test, fig_ref):
    """
    Check that setting a log scale sets good default axis limits
    when using pcolor.
    """
    x = np.linspace(0, 1, 11)
    # Ensuring second x value always falls slightly above 0.1 prevents flakiness with
    # numpy v1 #30882
    x[1] += 0.00001
    y = np.linspace(1, 2, 5)
    X, Y = np.meshgrid(x, y)
    C = X[:-1, :-1] + Y[:-1, :-1]

    ax = fig_test.subplots()
    ax.pcolor(X, Y, C)
    ax.set_xscale('log')

    ax = fig_ref.subplots()
    ax.pcolor(X, Y, C)
    ax.set_xlim(1e-1, 1e0)
    ax.set_xscale('log')


def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.hypot(X, Y) / 5

    _, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.pcolormesh(y, x, Z)

Review comment (suggestion):
```suggestion
    # numpy v1 #30882. This can be removed once we require numpy >= 2.
```
Just to be very clear to our future selfs.

Code after:
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z[:-1, :-1])
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z[:-1, :-1])
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30)


@check_figures_equal()
def test_pcolor_log_scale(fig_test, fig_ref):
    """
    Check that setting a log scale sets good default axis limits
    when using pcolor.
    """
    x = np.linspace(0, 1, 11)
    # Ensuring second x value always falls slightly above 0.1 prevents flakiness with
    # numpy v1 #30882. This can be removed once we require numpy >= 2.
    x[1] += 0.00001
    y = np.linspace(1, 2, 5)
    X, Y = np.meshgrid(x, y)
    C = X[:-1, :-1] + Y[:-1, :-1]

    ax = fig_test.subplots()
    ax.pcolor(X, Y, C)
    ax.set_xscale('log')

    ax = fig_ref.subplots()
    ax.pcolor(X, Y, C)
    ax.set_xlim(1e-1, 1e0)
    ax.set_xscale('log')


def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.hypot(X, Y) / 5

    _, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.pcolormesh(y, x, Z)
Repository: matplotlib/matplotlib
File: galleries/examples/lines_bars_and_markers/barh.py (Python)

Code before:
"""
====================
Horizontal bar chart
====================

This example showcases a simple horizontal bar chart.
"""
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
performance = [5, 7, 6, 4, 9]
error = [0.2, 0.4, 0.3, 0.6, 0.2]

ax.barh(people, performance, xerr=error, align='center')
ax.yaxis.set_inverted(True)  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

# %%
# .. tags::
#
#    plot-type: bar
#    level: beginner


Review comment (suggestion):
```suggestion
ax.yaxis.set_inverted(True)  # arrange data from top to bottom
```

Code after:
"""
====================
Horizontal bar chart
====================

This example showcases a simple horizontal bar chart.
"""
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
performance = [5, 7, 6, 4, 9]
error = [0.2, 0.4, 0.3, 0.6, 0.2]

ax.barh(people, performance, xerr=error, align='center')
ax.yaxis.set_inverted(True)  # arrange data from top to bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

# %%
# .. tags::
#
#    plot-type: bar
#    level: beginner