Issue
I want to create a line plot with custom marker style. I specifically want a square (filled/unfilled) with a plus or product symbol in it. How to do this. The following code doesn't work
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a figure and axis
fig, ax = plt.subplots()
# Define the custom marker as a combination of a filled square and a plus symbol
def custom_marker():
square = mpatches.Rectangle((-0.5, -0.5), 1, 1, linewidth=0, edgecolor='none', facecolor='red', zorder=2)
plus = plt.Line2D([0, 0], [-0.4, 0.4], color='white', linewidth=2, zorder=3)
plus2 = plt.Line2D([-0.4, 0.4], [0, 0], color='white', linewidth=2, zorder=3)
return [square, plus, plus2]
# Create a scatter plot with the custom marker style
ax.scatter(x, y, label="Data", marker=custom_marker()[0], c='blue', s=30)
# Customize the legend with the same custom marker
legend_marker = custom_marker()
ax.legend(handles=legend_marker, labels=["Custom Marker"])
# Display the plot
plt.show()
Solution
you could use a custom marker based on a Path
for this...
This way, the legend also works as expected.
import matplotlib.pyplot as plt
from matplotlib.path import Path
vertices=[[-15., -15.],
[-15., 15.],
[ 15., 15.],
[ 15., -15.],
[-15., -15.],
[-13., -13.],
[ 13., -13.],
[ 13., 13.],
[-13., 13.],
[-13., -13.],
[ -9., -1.],
[ -1., -1.],
[ -1., -9.],
[ 1., -9.],
[ 1., -1.],
[ 9., -1.],
[ 9., 1.],
[ 1., 1.],
[ 1., 9.],
[ -1., 9.],
[ -1., 1.],
[ -9., 1.],
[ -9., -1.]]
codes=[Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,]
p = Path(vertices=vertices, codes=codes)
fig, ax = plt.subplots()
ax.plot([1,2,3], [1,2,3], marker=p, ms=12, label="custom path marker")
plt.legend()
Update
It is also possible to fill the marker by drawing a rectangle with a "x" and using the edgecolor to color the "x" (this will also add a border to the rectangle... I'm not sure how to avoid this without plotting the rectangle and the x separately)
import matplotlib.pyplot as plt
from matplotlib.path import Path
vertices=[[-16, -16],
[-16, 16],
[ 16, 16],
[ 16, -16],
[-16, -16],
[ 0, 10],
[ 0, -10],
[-10, 0],
[ 10, 0]]
codes=[Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY,
Path.MOVETO,
Path.LINETO,
Path.MOVETO,
Path.LINETO
]
p = Path(vertices=vertices, codes=codes)
fig, ax = plt.subplots()
ax.plot([1,2,3], [1,2,3], marker=p, ms=12, label="custom path marker",
markerfacecolor="r", markeredgecolor="k", markeredgewidth=1.5)
plt.legend()
Answered By - raphael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.