2

I need to do what has been explained for MATLAB here: How to show legend for only a specific subset of curves in the plotting?

But using Python instead of MATLAB.

Brief summary of my goal: when plotting for example three curves in the following way

from matplotlib import pyplot as plt
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
# these are the curves
plt.plot(a)
plt.plot(b)
plt.plot(c)
plt.legend(['a','nothing','c'])
plt.show()

Instead of the word "nothing", I would like not to have anything there.

3sm1r
  • 520
  • 4
  • 19

1 Answers1

2

Using '_' will suppress the legend for a particular entry as following (continue reading for handling underscore _ as a legend). This solution is motivated by the recent post of @ImportanceOfBeingEarnest here.

plt.legend(['a','_','c'])

I would also avoid the way you are putting legends right now because in this way, you have to make sure that the plot commands are in the same order as legend. Rather, put the label in the respective plot commands to avoid errors.

That being said, the straightforward and easiest solution (in my opinion) is to do the following

plt.plot(a, label='a')
plt.plot(b)
plt.plot(c, label='c')
plt.legend()

enter image description here

As @Lucas pointed out in comment, if you want to show an underscore _ as the label for plot b, how would you do it. You can do it using

plt.legend(['a','$\_$','c'])

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • 1
    What if you want to name your plot `_` literaly? – Lucas Sep 25 '18 at 15:19
  • 1
    Do you mean `_ = plt.plot(b)` and then `plt.legend(['a','_','c'])`. It works in that case too although you get a user warning. That's why the second method I wrote is the way to go – Sheldore Sep 25 '18 at 15:21
  • 1
    I think he meant that he might want to have the low bar in the legend, like naming a curve 'e_4' – 3sm1r Sep 25 '18 at 15:23
  • No, that's not what he meant because you can easily do `plt.legend(['a_4','','c'])` – Sheldore Sep 25 '18 at 15:25
  • Yes, naming the curve `_` only, like: `plt.plot(a, label='_')` Is there any way to show that legend? – Lucas Sep 25 '18 at 15:26
  • 2
    @Lucas: Yes, you can do it as `plt.legend(['a','$\_$','c'])`. I added your suggestion in my answer – Sheldore Sep 25 '18 at 15:28
  • Who downvoted you? You provided a precise, complete and clear answer. – 3sm1r Sep 25 '18 at 15:43