Data Visualization With Python

4. Labeling Charts

Any good chart needs labels, a title, a legend, and gridlines (if appropriate).

To add axis labels, you can specify them by using the plt.xlabel() and plt.ylabel() function. Titles can be added using the plt.title() function.

What if you want to move the title or labels? Add the loc parameter to the corresponding function with a value of “left”, “right”, or “center."

You can also specify the font in a Python dictionary and use the fontdict parameter to adjust the font, size, and color.

Adding grid lines is as easy as adding plt.grid() to your code. If you want to add grid lines only for one axis, you can specify which axis by adding an axis parameter. Additionally, like the line graph, you can change the color, width, and style of the gridlines by using the same parameters outlined in Lesson 2.

When plotting multiple lines with different colors, adding a legend allows you to clearly define each line. Just add the label in a label parameter as part of your plot() functions. Then, at the end of your code, you can add plt.legend(), which will make the legend appear. If you want to change the appearance or style of the legend, look into the documentation of plt.legend() here: .

Sometimes, instead of plotting two sets of data on the same plot, you might want to plot them on side-by-side plots. You can do this using the subplot feature in Matplotlib. The subplot() function takes three arguments: rows, columns, and the current plot’s index.

For example, inserting plt.subplot(2,3,4) above a snippet of code plotting a line indicates that you want to plot that line as the fourth plot of a 2 rows by 3 columns plot. The plot index is determined going left to right so this would be the first plot in the second row.

Below is an example of using the subplot() function.

So far, you’ve learned how to plot line charts and customize them in a variety of different ways. The next lesson will showcase how to create other types of plots.