In Matplotlib, markers are used in plotting functions to highlight the data points on a plot. They can be customized in various ways, including changing their shape, color, size, and more. Here’s a quick overview of how to use markers in Matplotlib.
To use markers, you generally use the marker
parameter in plotting functions like plt.plot()
, plt.scatter()
, etc.
import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] # Plot with markers plt.plot(x, y, marker='o') plt.show()
Here are some of the common marker styles you can use:
'o'
: Circle'^'
: Triangle Up'v'
: Triangle Down's'
: Square'p'
: Pentagon'*'
: Star'+'
: Plus'x'
: X'.'
: PointYou can customize the markers further by using parameters such as markersize
, markeredgewidth
, markeredgecolor
, and markerfacecolor
.
plt.plot(x, y, marker='o', markersize=10, markeredgewidth=2, markeredgecolor='red', markerfacecolor='yellow') plt.show()
In scatter plots, markers are crucial since each point is typically represented by a marker.
plt.scatter(x, y, s=100, c='blue', marker='^') # s is the marker size plt.show()
Here’s a more complete example that demonstrates various markers and customizations:
import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5] y1 = [1, 4, 9, 16, 25] y2 = [2, 3, 5, 7, 11] # Different markers for different plots plt.plot(x, y1, marker='o', markersize=8, markeredgewidth=1, markeredgecolor='blue', markerfacecolor='green', label='Squares') plt.plot(x, y2, marker='^', markersize=10, markeredgewidth=2, markeredgecolor='red', markerfacecolor='yellow', label='Primes') # Adding labels and title plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Plot with Custom Markers') plt.legend() # Show plot plt.show()