How to Set Line Color in Matplotlib: Simple Guide
To set the line color in Matplotlib, use the
color parameter inside the plot() function. You can specify colors by name, hex code, or shorthand letters like 'r' for red.Syntax
The basic syntax to set line color in Matplotlib is using the color parameter inside the plot() function.
color: Defines the line color. It accepts color names (e.g., 'blue'), hex codes (e.g., '#FF5733'), or single-letter shortcuts (e.g., 'g' for green).
python
plt.plot(x, y, color='color_value')Example
This example shows how to plot a simple line graph with a red line using the color parameter.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, color='red') plt.title('Line plot with red color') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A line plot with points connected by a red line.
Common Pitfalls
Common mistakes when setting line color include:
- Using an invalid color name or code, which causes an error.
- Confusing the
colorparameter withcorfacecolorwhich are used in other plot types. - Not specifying the
colorparameter inside theplot()call.
Here is an example showing a wrong and right way:
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [4, 5, 6] # Wrong: invalid color name # plt.plot(x, y, color='redd') # This will cause an error # Right: valid color name plt.plot(x, y, color='red') plt.show()
Output
A line plot with a red line connecting points (1,4), (2,5), (3,6).
Quick Reference
| Color Parameter Value | Description | Example |
|---|---|---|
| 'red' | Named color | color='red' |
| 'r' | Single letter shortcut | color='r' |
| '#00FF00' | Hex color code | color='#00FF00' |
| 'blue' | Named color | color='blue' |
| 'g' | Single letter shortcut | color='g' |
Key Takeaways
Use the color parameter inside plt.plot() to set line color.
Colors can be named strings, hex codes, or single-letter shortcuts.
Invalid color names cause errors, so use valid color values.
The color parameter must be inside the plot() call to work.
Common shortcuts include 'r' for red, 'g' for green, and 'b' for blue.