We created a basic line chart just by supplying x
and y
parameters to the .plot()
function. Once we have more than one line in the chart, matplotlib will automatically style them with different colors, always in the same order (the first line is blue, the second is orange, and so on). This is helpful, but we’ll get a more consistent result by controlling line formatting ourselves rather than leaving it to the default option.
To change the line color, we can simply pass an argument to the color
parameter in .plot()
. This argument is always a string, and it can be one of three options:
- single-letter color code (8 basic colors)
- full string color (1000+ recognized colors)
- hexadecimal code (any web color)
# single-letter color code plt.plot(x, y, color='r') # full string plt.plot(x, y, color='red') # hex code plt.plot(x, y, color='#FF0000')
All three code snippets above will produce a single red line on the line chart. We’ll see this code live in the Jupyter notebook.
In addition to color
, .plot()
will take the parameters linewidth
and linestyle
. linewidth
takes a number that changes the thickness of the line. linestyle
takes a string: dotted
, dashed
, or solid
.
# dashed red line plt.plot(x, y, color='r', linestyle='dashed') # thick, solid yellow line plt.plot(x, y, color='yellow', linewidth=5) # thin, dotted white line plt.plot(x, y, color='#FFFFFF', linewidth=0.5, linestyle='dotted')
Instructions
Run the Setup blocks. Then run the next three code blocks to compare the red line graphs.
Add a color parameter to use color to group lines by hemisphere.
- Make the line color for all of the cities in the Southern Hemisphere
'green'
. Those cities are Alice Springs (Australia) and Windhoek (Namibia). - Make the line color for Quito the color
'steelblue'
. Quito is technically in the Southern Hemisphere, but lies almost exactly on the equator. - Make the line color for all of the cities in the Northern Hemisphere
'darkorange'
. Those cities are Kodiak (Alaska, US), Samarqand (Uzbekistan), and London (UK).
Finally, we’ll use linestyle
to differentiate lines of the same color.
- We have two green lines. Give Alice Springs a
dotted
line and Windohoek adashed
line. - Quito is the only blue line, and we’ll keep it solid. You can specify this using the
linestyle
parameter, or leave it blank since all lines default tosolid
. Either way, change the line width to 2.5. - We have three dark orange lines. Give Kodiak a
solid
line, Samarqand adotted
line, and London adashed
line.