-: Hi Guys, and welcome back.
In this video, we're going to learn
how to add a legend to our charts,
so that it's a bit easier to see
what colours mean what in the plot.
So, let's get started.
Here we've got our chart from the last section,
and we're going to press Play in here,
and you can see that we get our chart.
And we've got the blue and the orange colours,
but it's not entirely clear what they mean.
So, that's where the legend is gonna come into play.
The first thing to do is to go ahead into our bar call here,
and we're going to add a label.
The label can be added to basically any plot.
And it is used if you want to, when creating a legend.
So, we're going to do men,
and then in here, we're going to do label equal women.
Now, just doing this won't do everything that we want.
We've now given the plots a label,
but we've not asked pyplot to create a legend.
So, that's the next bit.
We have to go ahead and down here,
say axes dot legend,
and that is going to generate a legend
for the axes then have these plots.
So, we can run it again.
And now you can see we get men and women there.
Pyplot is actually pretty smart with a legend.
It's not always appearing in the top right hand corner.
If you've got some short bars here and some long bars here,
pyplot is often smart enough to move this over to the left.
And, but it's not always perfect,
so just bear that in mind as well.
So, this was the first and simplest way
of defining a legend.
However, sometimes it can be useful
to manually assign a legend item to individual plots.
So, let's do that.
We're gonna get rid of these labels,
and instead, we're going to assign these plots
to specific variables.
So, we'll say men plot equal that,
and women plot equal that.
Now, when we've got this,
we can then use them when we're creating our legends.
So, what we do is in here,
in the legend call, we pass in a tuple of plots.
So, that's men plot and women plot.
And then another tuple of labels.
So, that's men and women.
As you can see, that produces exactly the same output.
I'm not entirely sure which one I prefer just yet.
In this one, the legend is defined in one place,
which is nice in terms of readability.
But when you assign a label to each plot,
then you allow pyplot to generate the legend for you
from all the plots in the axes.
So, it's up to you whether you want to create a legend
for everything that has a label,
or just for the things in here.
And, but I wanted to show you both ways
because they both can come in handy in different situations.
Alright. Thank you guys for joining me in this video.
Thanks for watching, and I'll see you in the next one.