I would like to add a manual legend to a matplotlib plot of this nature:
While I managed to add the horizontal bars to my legend, I am stuck with the creation of the horizontal error bars.
I based my approach on this StackOverflow answer.
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.container import ErrorbarContainer
from matplotlib.lines import Line2D
from matplotlib.collections import LineCollection
fig, ax = plt.subplots(
figsize=(2, 2),
)
line = plt.Line2D(
xdata = [],
ydata = [],
color = 'black',
linestyle='none'
)
barline = LineCollection(
segments = [
[(0, 0), (0, 1)],
]
)
err = ErrorbarContainer(
lines = (
line,
[line],
[barline],
),
has_xerr = True,
has_yerr = False,
)
legend_elements = [
Patch(facecolor='red', edgecolor='black', label='Average Warming'),
Patch(facecolor='blue', edgecolor='black', label='Average Cooling'),
err,
]
# Displaying the custom legend
fig.legend(
handles=legend_elements,
loc=10
)
Error:
---> 26 err = ErrorbarContainer(
27 lines = (
28 line,
29 [line],
30 [barline],
31 ),
32 has_xerr = True,
33 has_yerr = False,
34 )
36 legend_elements = [
37 Patch(facecolor='red', edgecolor='black', label='Average Warming'),
38 Patch(facecolor='blue', edgecolor='black', label='Average Cooling'),
39 err,
40 ]
42 # Displaying the custom legend
File /opt/homebrew/Caskroom/miniconda/base/envs/plotting/lib/python3.11/site-packages/matplotlib/container.py:18, in Container.__new__(cls, *args, **kwargs)
17 def __new__(cls, *args, **kwargs):
---> 18 return tuple.__new__(cls, args[0])
IndexError: tuple index out of range
Should it not be enough to specify one line in the barlinecols
parameter, since I am only interested in the horizontal (=x) error? After all, according to the documentation:
barlinecols
: list of LineCollection with the horizontal and vertical error ranges.