Learn to Code via Tutorials on Repl.it

← Back to all posts
harpertutorial - Plotting Graphs
HarperframeInc (247)

Plotting Graphs...

You do that in math, science, and in python too!
First, we need to import matplotlib


NOTE
matplotlib is a looooong name. Use as mpl instead.
I will be referring to it as mpl.


So, what's next?
Let's start your first simple graph.

# DON'T EVER USE:
import matplotlib as mpl
# ALWAYS USE:
import matplotlib.pyplot as mpl

So we imported mpl. What's next?
We can create a line graph with:

import matplotlib.pyplot as mpl
mpl.plot([1, 2, 3, 4], [1, 4, 9, 16])

Doing this will give us:

Do you like it?
Mess around with it, do whatever you want!

Labeling

Labels, Labels, Labels.
Your X axis, your Y axis.
You can label your X & Y axis with:

import matplotlib.pyplot as mpl
mpl.plot([1, 2, 3, 4], [1, 4, 9, 16])
mpl.xlabel("X Label")
mpl.ylabel("Y Label")

Here's an example the Pyplot Guide gives:

Saving and Showing.

You can show with the:

mpl.show()

Or you want to download it,

mpl.save()

Bonus

Eww, I hate that blue line. Why is it there?
Well,

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')

Gives you...
Drumroll Please....

Wow!
The blue line is because all graphs default to "-b"
How about the red circles? Its "ro"
How about all colors and shapes?
Here's what the guide has to say.

Colors
The following color abbreviations are supported:
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
Markers
'.' point marker
',' pixel marker
'o' circle marker
'v' triangledown marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'
' hline marker
Line Styles
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
Please don't ask me questions about this, because I literally have no clue on shapes and stuff, I can help with anything else. Here's the guide on the plot() function: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot

Liked this tutorial? Was it anyway helpful to you? If so, please upvote this tutorial. I might be adding on more soon.

The Guide: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
Use the code below for reference

Commentshotnewtop
UVIANAnD (0)

These examples aren't working for me, and I have tried similar tutorials that also don't output anything after hitting "Run". What could be wrong?
The very first example does nothing. It also does nothing if you use "mpl.show()", and you get an error if you try "mpl.save()".

timmy_i_chen (1021)

Awesome - thanks for making this!