How to add a marker to a line size in Matplotlib
Overview
Markers are used in matplot library (matplotlib) to simply enhance the visual of line size of a plot. You can use the keyword argument marker to emphasize which marker you want on the line of plot.
Marker references in Python
Below is a table showing the list of some markers present in the matplot library and their respective descriptions.
| Marker | Description |
|---|---|
| ‘*’ | Star |
| ‘o’ | Circle |
| ‘.’ | Point |
| ‘x’ | X |
| 'X | X (filled) |
| ‘D’ | Diamond |
| ‘d’ | Thin diamond |
| ‘p’ | Pentagon |
| ‘H’ | Hexagon |
| ‘h’ | hexagon |
| ‘+’ | Plus |
| ‘P’ | Plus (filled) |
| ‘,’ | Pixel |
| ‘s’ | Square |
| ‘v’ | Triangle down |
| ‘^’ | Triangle up |
| ‘>’ | Triangle right |
| ‘<’ | Triangle left |
| ‘1’ | Tri down |
| ‘2’ | Tri up |
| ‘3’ | Tri left |
| ‘4’ | Tri right |
| ‘|’ | Vine |
| ‘-’ | Hline |
| (numsides, style, angle) | This marker can also be a tuple (numsides, style, angle), which will create a custom, regular symbol. |
| path | A Path instance. |
| verts | A list of (x, y) pairs used for Path vertices. The center of the marker is located at (0,0) and the size is normalized, such that the created path is encapsulated inside the unit cell. |
From the table above, we can see that in matplotlib, markers take different symbols: ‘H’ for hexagon marker, ‘s’ for star marker, ‘d’ for thin diamond marker, etc.
How to add markers to the line size of a plot
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltx=[1, 2, 3, 4, 5, 6]y=[2, 4, 6, 8, 10, 12]# using a point '.' markerplt.plot(x,y,linewidth=2, marker ='.')plt.show()
Explanation
- Line 1: We imported
pandasas we gave it a name,pd. - Line2: We imported
numpyas we gave it a name,np. - Line 3: We imported
matplotlib.pyplotasplt. - Line 5: We created a variable.
- Line 6: We created another variable,
y. - Line 8: We called the
pltfunction, i.e., thepyplotfunctionplt.plotto help us plot a graph ofxagainsty. The line width of the graph should be of size2. Then, finally, the marker should be of the fullstop ‘.’ sign usingmarker ='.'
Now, let’s make subplots showing various markers.
import numpy as npimport matplotlib.pyplot as plt# Fixing random state for reproducibilitynp.random.seed(19680801)x=[1, 2, 3, 4, 5, 6]y=[2, 4, 6, 8, 10, 12]fig, axs = plt.subplots(2, 3)# Triangular right markeraxs[0, 0].scatter(x, y, s=80, marker=">")axs[0, 0].set_title("marker='>'")# pentagon markeraxs[0, 1].scatter(x, y, s=80, marker='p')axs[0, 1].set_title(r"marker='Pentagon'")# marker from pathverts = [[-1, -1], [1, -1], [1, 1], [-1, -1]]axs[0, 2].scatter(x, y, s=80, marker=verts)axs[0, 2].set_title("marker=verts")# V line markeraxs[1, 0].scatter(x, y, s=80, marker='|')axs[1, 0].set_title("marker=Vline")# Star markeraxs[1, 1].scatter(x, y, s=80, marker=('*'))axs[1, 1].set_title("marker=Star")# regular asterisk markeraxs[1, 2].scatter(x, y, s=80, marker=(5, 2))axs[1, 2].set_title("marker=(5, 2)")plt.tight_layout()plt.show()