Module 5 · Matplotlib · Lesson 27 of 66
Labels, legends and styles
Legends, colors, line widths, markers and axis ranges.
In this lesson · about 14 minutes
- Add a legend from line labels
- Style lines with color, width, style and markers
- Set the visible range with set_xlim and set_ylim
Give each line a label="…" when you plot it, then call ax.legend(). Matplotlib picks a spot that covers the least data; choose one yourself with loc, such as ax.legend(loc='upper left').
Colors and line styles
- Quick codes, borrowed from MATLAB:
'b.-'is a blue line with dots,'g--'a green dashed line. - Clearer keywords:
color='#8B008B'(a name or hex code) andalpha=0.5for transparency. linewidthorlwsets thickness;linestyleorlspicks'-','--','-.'or':'.marker='o'marks each point, withmarkersize,markerfacecolorand friends to style it.
Axis range
ax.set_xlim([low, high]) and ax.set_ylim([low, high]) choose what part of the chart is visible, which is handy to zoom in.
Exercise
Two labeled lines
On one set of axes, plot x ** 2 labeled 'square' and x ** 3 labeled 'cube', then add a legend in the upper left.
Code that runs before yours
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 5, 11) y = x ** 2
Exercise
A styled line
Plot x against y in 'purple', line width 3, dotted (':'), with circle markers ('o').
Code that runs before yours
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 5, 11) y = x ** 2
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.