First of all, here's the root of the
documentation:
https://matplotlib.org/
The
Gallery
shows how flexible this graphics library is.
To install it into Thonny:
- First check to see if it's already installed. In the
shell, type "import matplotlib"
- If not installed, go to menu: Tools/Manage packages, type
"matplotlib" in the text box, click on "Find package...", and then
click on Install
- Then try Step #1
For the code below, import it using:
import matplotlib.pyplot as plt
"plt" is an abbreviation for "matplotlib.pyplot" to save us from
finger fatigue.
|
Here are the basic plotting functions:
plt.plot(y_data) or
plt.plot(x_data,y_data)
y_data is a list of values that will be plotted
(graphed) on the y-axis
x_data, if included, will be the corresponding x-values
plt.plot([1,4,9,16,25])
plt.plot([1,2,3,4],[1,4,9,16]) will plot the points: (1,1),
(2,4), (3,9) and (4,16)
plt.plot(x_data,y_data,label=some-string-identifying-thisdata)
plt.show()
Actually display the plot (do this as the last
step in building up a plot)
plt.title(some_title)
Registers the title that will be shown for the
plot
plt.ylabel(a_label), plt.xlabel(another_label)
creates labels for the axes
plt.axis([xmax, xmin, ymax, ymin])
sets the limits for the axes
plt.legend(some_text)
display a legend (colored labels) for the graph
plt.scatter(x_data, y_data, scale)
creates a scatter plot, scale sets the size of
the dots
|
Simple Examples:
import matplotlib.pyplot as plt
import random
# Simple plot of squares
def one():
data = []
for i in range(100):
data.append(i*i)
plt.plot(data)
plt.show()
# Scatter plot of squares
def two():
data = []
for i in range(100):
data.append(i*i)
plt.scatter(list(range(100)),data,1)
plt.show()
# Scatter (or normal graph) with random noise added
def three():
data = []
for i in range(100):
y = i*i
y += random.random()*y/10
data.append(y)
plt.scatter(list(range(100)),data,10)
#plt.plot(data)
plt.legend('Squares')
plt.axis([0,100,0,10000])
plt.show()
# Two graphs in the same display
def four():
data_1 = []
data_2 = []
for i in range(10):
data_1.append(i*i)
data_2.append(i*i*i)
x_data = list(range(10))
plt.plot(x_data,data_1,label='squares')
plt.plot(x_data,data_2,label='cubes')
plt.title('Simple')
plt.legend() # display the labels
plt.show()
|