Skip to content

Commit

Permalink
Fix plot legend don't show up when dataset start with zero (#10176)
Browse files Browse the repository at this point in the history
* added test to plot_histogram with dataset starting with zero

* fixed plot_histogram

* added docs

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
(cherry picked from commit 645598a)
  • Loading branch information
Dpbm authored and mergify[bot] committed Jul 13, 2023
1 parent 91cfe31 commit 07ce24d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion qiskit/visualization/counts_visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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 <https://github.com/Qiskit/qiskit-terra/issues/10158>` for more details.
13 changes: 13 additions & 0 deletions test/python/visualization/test_plot_histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 07ce24d

Please sign in to comment.