Matplotlib by default includes errorbars in the legend on top of whatever symbol is
being used. I think this makes the legend look really messy, so wanted to remove it
and simply plot the symbols. Here is a legend with errorbars included:
The simple way fix this is to double plot the data, with the errorbars on top, but only
label the non errorbar plot:
This works fine, but is very un-pythonic, and feels like a bad way to do this for large datasets.
So lets do it properly by removing the line objects from the legend objects:
This gets the artists for each item in the legend, handles. For each errorbar
object, the first item, handles corresponds to the symbol, and the other items
correspond to the errorbars. So by looping through all of the items in the legend,
and using isinstance to check for errorbar objects and building a new list for handles
new_handles which contains unmodified artists for non-errorbar objects and only the
symbol for errorbars themselves.
That’s quite a lot of code to do a simple thing, and I’d rather not create a second list. So,
lets tidy this up and use a ternary operator to make this a bit more streamlined:
The final fixed legend looks the same all of these methods: