diff --git a/qiskit/visualization/counts_visualization.py b/qiskit/visualization/counts_visualization.py index ad9ec4536ccc..8e743254bc3c 100644 --- a/qiskit/visualization/counts_visualization.py +++ b/qiskit/visualization/counts_visualization.py @@ -343,8 +343,8 @@ def _plotting_core( labels_dict, all_pvalues, all_inds = _plot_data(data, labels, number_to_keep, kind=kind) rects = [] for item, _ in enumerate(data): + label = None for idx, val in enumerate(all_pvalues[item]): - label = None if not idx and legend: label = legend[item] if val > 0: @@ -358,6 +358,7 @@ def _plotting_core( zorder=2, ) ) + label = None bar_center = (width / 2) * (length - 1) ax.set_xticks(all_inds[item] + bar_center) ax.set_xticklabels(labels_dict.keys(), fontsize=14, rotation=70) diff --git a/releasenotes/notes/fix-plot-legend-not-showing-up-3202bec143529e49.yaml b/releasenotes/notes/fix-plot-legend-not-showing-up-3202bec143529e49.yaml new file mode 100644 index 000000000000..375aab340dcb --- /dev/null +++ b/releasenotes/notes/fix-plot-legend-not-showing-up-3202bec143529e49.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Fixed plot legend error when your dataset has a zero value at first position. + When one of your counts or distributions had a zero value at first position, the relative legend didn't show up. + See `#10158 ` for more details. diff --git a/test/python/visualization/test_plot_histogram.py b/test/python/visualization/test_plot_histogram.py index c986388289e3..f44cef3d0ece 100644 --- a/test/python/visualization/test_plot_histogram.py +++ b/test/python/visualization/test_plot_histogram.py @@ -214,6 +214,19 @@ def test_with_number_to_keep_multiple_executions_correct_image(self): mpl.pyplot.close(figure_ref) mpl.pyplot.close(figure_truncated) + @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.") + def test_number_of_items_in_legend_with_data_starting_with_zero(self): + """Test legend if there's a 0 value at the first item of the dataset""" + dist_1 = {"0": 0.369, "1": 0.13975} + dist_2 = {"0": 0, "1": 0.48784} + legend = ["lengend_1", "lengend_2"] + plot = plot_histogram([dist_1, dist_2], legend=legend) + self.assertEqual( + len(plot._localaxes[0].legend_.texts), + 2, + "Plot should have the same number of legend items as defined", + ) + if __name__ == "__main__": unittest.main(verbosity=2)