Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_legend.py (Python)

Code before:
    assert [v.get_label() for v in bp2['medians']] == legend_labels
    handles, labels = axs[1].get_legend_handles_labels()
    assert labels == legend_labels
    assert all(isinstance(h, mpl.lines.Line2D) for h in handles)

    # Testing legend with number of labels different from number of boxes.
    with pytest.raises(ValueError, match='values must have same the length'):
        bp3 = axs[2].boxplot(data, label=legend_labels[:-1])

    # Test that for a string label, only the first box gets a label.
    bp4 = axs[3].boxplot(data, label='box A')
    assert bp4['medians'][0].get_label() == 'box A'
    assert all(x.get_label().startswith("_") for x in bp4['medians'][1:])


def test_patchcollection_legend():
    # Test that PatchCollection labels show up in legend (issue #23998)
    fig, ax = plt.subplots()

    # Create some patches
    p1 = mpatches.Polygon([[0, 0], [100, 100], [200, 0]])
    p2 = mpatches.Polygon([[400, 0], [500, 100], [600, 0]])

    # Create a PatchCollection with a label
    pc = mcollections.PatchCollection([p1, p2], label="patch collection",
                                      facecolor='blue', edgecolor='black')
    ax.add_collection(pc, autolim=True)
    ax.autoscale_view()

    # Create the legend
    leg = ax.legend()

    # Check that the legend contains our label
    assert len(leg.get_texts()) == 1
    assert leg.get_texts()[0].get_text() == "patch collection"

    # 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)

Review comment (suggestion):
More compact:
```suggestion
    pc = mcollections.PatchCollection(
        [
            mpatches.Polygon([[0, 0], [100, 100], [200, 0]]),
            mpatches.Polygon([[400, 0], [500, 100], [600, 0]]),
        ],
        label="patch collection", facecolor='blue', edgecolor='black'
    )
```

Code after:
    assert [v.get_label() for v in bp2['medians']] == legend_labels
    handles, labels = axs[1].get_legend_handles_labels()
    assert labels == legend_labels
    assert all(isinstance(h, mpl.lines.Line2D) for h in handles)

    # Testing legend with number of labels different from number of boxes.
    with pytest.raises(ValueError, match='values must have same the length'):
        bp3 = axs[2].boxplot(data, label=legend_labels[:-1])

    # Test that for a string label, only the first box gets a label.
    bp4 = axs[3].boxplot(data, label='box A')
    assert bp4['medians'][0].get_label() == 'box A'
    assert all(x.get_label().startswith("_") for x in bp4['medians'][1:])


def test_patchcollection_legend():
    # Test that PatchCollection labels show up in legend and preserve visual
    # properties (issue #23998)
    fig, ax = plt.subplots()

    pc = mcollections.PatchCollection(
        [mpatches.Circle((0, 0), 1), mpatches.Circle((2, 0), 1)],
        label="patch collection",
        facecolor='red',
        edgecolor='blue',
        linewidths=3,
        linestyle='--',
    )
    ax.add_collection(pc)
    ax.autoscale_view()

    leg = ax.legend()

    # Check that the legend contains our label
    assert len(leg.get_texts()) == 1
    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()