mcalf.utils.plot.hide_existing_labels(plot_settings, axes=None, fig=None)[source]

Hides labels for each dictionary provided if label already exists in legend.

  • plot_settings (dict of {str: dict}) – Dictionary of lines to be plotted. Values must be dictionaries with a ‘label’ entry that this function my append with a ‘_’ to hide the label.

  • axes (list of matplotlib.axes.Axes, optional, default=None) – List of axes to extract lines labels from. Extracts axes from fig if omitted.

  • fig (matplotlib.figure.Figure, optional, default=None) – Figure to take line labels from. Uses current figure if omitted.


Only the plot_settings[*]['label'] values are uses to assess if a label has already been used. Other plot_settings parameters such as color are ignored.


Import plotting package:

>>> import matplotlib.pyplot as plt

Define various plot settings:

>>> plot_settings = {
...     'LineA': {'color': 'r', 'label': 'A'},
...     'LineB': {'color': 'g', 'label': 'B'},
...     'LineC': {'color': 'b', 'label': 'C'},
... }

Create a figure and plot two lines on the first axes:

>>> fig, axes = plt.subplots(1, 2)
>>> axes[0].plot([0, 1], [0, 1], **plot_settings['LineA'])  
[<matplotlib.lines.Line2D object at 0x...>]
>>> axes[0].plot([0, 1], [1, 0], **plot_settings['LineB'])  
[<matplotlib.lines.Line2D object at 0x...>]

Set labels already used to be hidden if used again:

>>> hide_existing_labels(plot_settings)

Anything already used will have an underscore prepended:

>>> [x['label'] for x in plot_settings.values()]
['_A', '_B', 'C']

Plot two lines on the second axes:

>>> axes[1].plot([0, 1], [0, 1], **plot_settings['LineB'])  # Label hidden  
[<matplotlib.lines.Line2D object at 0x...>]
>>> axes[1].plot([0, 1], [1, 0], **plot_settings['LineC'])  
[<matplotlib.lines.Line2D object at 0x...>]

Show the figure with the legend:

>>> fig.legend(ncol=3, loc='upper center')  
<matplotlib.legend.Legend object at 0x...>
>>> plt.show()  
>>> plt.close()