Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to draw more type of lines in Matplotlib?
To draw different types of lines in Matplotlib, you can customize line styles using various parameters like dashes, line width, and color. This allows you to create dashed, dotted, or custom dash patterns for better visualization.
Steps to Draw Custom Lines
- Set the figure size and adjust the padding between and around the subplots
- Create x and y data points using NumPy
- Plot x and y data points using
plot()method with custom line parameters - To display the figure, use
show()method
Example − Custom Dash Pattern
Here's how to create a line with a custom dash pattern ?
from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-10, 10, 100) y = np.sin(x) plt.plot(x, y, dashes=[1, 1, 2, 1, 3], linewidth=7, color='red') plt.show()
Different Line Styles
Matplotlib provides several predefined line styles and the ability to create custom patterns ?
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x + 0.5)
y4 = np.cos(x + 0.5)
plt.figure(figsize=(10, 6))
# Solid line
plt.plot(x, y1, '-', label='Solid', linewidth=2)
# Dashed line
plt.plot(x, y2, '--', label='Dashed', linewidth=2)
# Dotted line
plt.plot(x, y3, ':', label='Dotted', linewidth=2)
# Dash-dot line
plt.plot(x, y4, '-.', label='Dash-dot', linewidth=2)
plt.legend()
plt.title('Different Line Styles')
plt.show()
Custom Dash Patterns
Create your own dash patterns by specifying the dash sequence ?
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(10, 8)) # Different custom dash patterns plt.subplot(3, 1, 1) plt.plot(x, y, dashes=[5, 2], label='Long dash, short gap', linewidth=3) plt.legend() plt.subplot(3, 1, 2) plt.plot(x, y, dashes=[2, 2, 10, 2], label='Short-long-short pattern', linewidth=3, color='green') plt.legend() plt.subplot(3, 1, 3) plt.plot(x, y, dashes=[1, 1, 1, 1, 5, 1], label='Complex pattern', linewidth=3, color='purple') plt.legend() plt.tight_layout() plt.show()
Line Style Parameters
| Parameter | Description | Example Values |
|---|---|---|
linestyle |
Predefined line styles | '-', '--', ':', '-.' |
dashes |
Custom dash pattern | [5, 2, 1, 2] |
linewidth |
Line thickness | 1, 2, 5, 10 |
color |
Line color | 'red', 'blue', '#FF5733' |
Conclusion
Matplotlib offers flexible line styling through predefined styles ('-', '--', ':', '-.') and custom dash patterns using the dashes parameter. Use these features to create visually distinct plots for better data presentation.
Advertisements
