Learn

This graph is starting to get interesting! It’s pretty hard to interpret, though, so let’s add a title and legend.

When we set the parameters for our line chart and changed line formatting, we did all of that inside the .plot() function. (Remember, .plot() is a graph function in matplotlib because it makes a line graph.)

To make the title and legend, we’re going to use two of matplotlib’s general functions.

To put a title on any graph, we simply type the title as a string into plt.title(). For example, plt.title(‘Effect of Hunger on Mood’) could go on a scatterplot showing a correlation between hunger level and mood. By default, the title is positioned at the top of the figure.

To make a legend, we use the general function plt.legend(). We use this general function to set up the legend, but in order to tell the legend function which line is which, we’ll also put a label argument inside each line function. .legend() uses .plot()’s label parameter as its information source.

plt.plot(x, y, color='red', label='Line Y') plt.plot(x, z, color='green', label='Line Z') plt.legend()

This code will produce a graph with a legend that identifies the red line as Line Y and the green line as Line Z.

To position the legend, we can use the plt.legend() parameter bbox_to_anchor, which takes an (x,y) coordinate pair as its argument. For the x-coordinate, 0 is the left edge of the graph and 1 is the right edge. For the y-coordinate, 0 is the bottom edge of the graph and 1 is the top. For example, plt.legend(bbox_to_anchor = (1, 0.5)) places the legend to the right of the figure (all the way at 1 on the x-coordinate), in the middle of the vertical space (0.5 on the y-coordinate).

plt.plot(x, y, color='red', label='Line Y') plt.plot(x, z, color='green', label='Line Z') plt.legend(bbox_to_anchor = (1, 0.5))

This code will make the same graph as above, with the legend positioned to the right of the graph.

Instructions

1.

Title the graph “Average High Temps Around the World, 2020”.

2.

Add the city name as a legend label to each line and create the legend.

3.

Position the legend at (1, 0.75).

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?