Line
What You'll Learn: In this tutorial, you'll discover how to draw and customize lines using Matplotlib in Python. We'll cover setting line color, changing line width, and plotting multiple lines.
Line Color
You can use the keyword argument color or the shorter c to set the color of the line.
Example: Set the line color to red:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, color='r')
plt.show()
Result:
You can also use Hexadecimal color values to set the color.
Example: Plot with a green line:
plt.plot(ypoints, c='#4CAF50')
plt.show()
Result:
Or use any of the 140 supported color names.
Example: Plot with the color named "hotpink":
plt.plot(ypoints, c='hotpink')
plt.show()
Result:
Line Width
You can use the keyword argument linewidth or the shorter lw to change the width of the line. The value is a floating number in points.
Example: Plot with a 20.5pt wide line:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linewidth='20.5')
plt.show()
Result:
Multiple Lines
You can plot multiple lines by simply adding more plt.plot() functions.
Example: Draw two lines:
import matplotlib.pyplot as plt
import numpy as np
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])
plt.plot(y1)
plt.plot(y2)
plt.show()
Result:
You can also plot many lines by adding the points for the x- and y-axis for each line in the same plt.plot() function.
Example: Draw two lines by specifying the x- and y-point values:
import matplotlib.pyplot as plt
import numpy as np
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])
plt.plot(x1, y1, x2, y2)
plt.show()
Result:
Try It Yourself: Fun Exercises
- Customize Line Colors:
- Experiment with different colors and hexadecimal values for your lines.
- Change Line Width:
- Try setting different line widths and observe how it affects the plot.
- Plot Multiple Lines:
- Create plots with multiple lines, using different x- and y-values.
Summary:
In this tutorial, we learned how to draw and customize lines using Matplotlib in Python. We explored setting line colors, changing line widths, and plotting multiple lines. Keep experimenting and have fun with Matplotlib in Python!