Plotting
What You'll Learn: In this tutorial, you'll discover how to use Matplotlib to plot points and lines on a graph. We'll cover basic plotting, plotting without lines, plotting multiple points, and using default x-points.
Plotting x and y Points
The plot() function is used to draw points (markers) in a diagram. By default, this function draws a line from point to point.
- Parameters:
- Parameter 1: An array containing the points on the x-axis.
- Parameter 2: An array containing the points on the y-axis.
Example Code:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints)
plt.show()
Result:
This example plots a line in a diagram from position (1, 3) to position (8, 10).
Plotting Without Lines
To plot only the markers, you can use the shortcut string notation parameter 'o', which means 'rings'.
Example Code:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()
Result:
This example draws two points in the diagram, one at position (1, 3) and one at position (8, 10).
Plotting Multiple Points
You can plot as many points as you like, just make sure you have the same number of points on both axes.
Example Code:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()
Result:
This example plots a line from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10).
Default X-Points
If you do not specify the points on the x-axis, they will get the default values 0, 1, 2, 3, etc., depending on the length of the y-points.
Example Code:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()
Result:
In this example, the x-points are [0, 1, 2, 3, 4, 5] by default.
Try It Yourself: Fun Exercises
- Modify the Line Plot:
- Change the coordinates in
xpointsandypointsto draw different lines and see how the plot changes.
- Change the coordinates in
- Plot More Points:
- Add more points to
xpointsandypointsto create more complex lines and shapes.
- Add more points to
- Experiment with Default X-Points:
- Try plotting only
ypointsand observe the default x-points.
- Try plotting only
Summary:
In this tutorial, we learned how to use Matplotlib to plot points and lines on a graph. We explored basic plotting, plotting without lines, plotting multiple points, and using default x-points. Keep experimenting and have fun with plotting in Python!