我想创建具有自定义标记样式的线图。我特别想要一个带有加号或乘积符号的正方形(填充/未填充)。这个怎么做。下面的代码不起作用
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()
Run Code Online (Sandbox Code Playgroud)
绘制两次怎么样?它似乎有效,并且您可以通过这种方式有更多选择:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 6.28, 20)
y = np.sin(x)
plt.plot(
x,
y,
linestyle='-',
color='c',
marker='s',
markersize=8,
markeredgewidth=1,
markeredgecolor='b',
markerfacecolor='orange',
)
plt.plot(
x,
y,
linestyle=' ',
color='c',
marker='+',
markersize=8,
markeredgewidth=1,
markeredgecolor='b',
markerfacecolor='orange',
)
plt.show()
Run Code Online (Sandbox Code Playgroud)
或者你可以使用这个来获得没有任何面部颜色的正方形:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 6.28, 20)
y = np.sin(x)
plt.plot(
x,
y,
linestyle='-',
color='#00a2ff',
marker='+',
markersize=8,
markeredgewidth=2,
markeredgecolor='#bc00ca',
)
plt.plot(
x,
y,
linestyle=' ',
marker='s',
markersize=12,
markeredgewidth=1,
markeredgecolor='b',
markerfacecolor='none',
#alpha=0.5,
)
plt.show()
Run Code Online (Sandbox Code Playgroud)
或者给markerfacecolor一个值,然后打开alpha来改变它的不透明度。
更新(在您提到图例问题之后)
既然你说填充或未填充,那么这里是未填充的:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 6.28, 20)
y = np.sin(x)
plt.plot(
x,
y,
linestyle="--",
color="r",
marker="$\\boxplus$",
markerfacecolor="r",
markersize="8",
markeredgewidth="0.1",
)
plt.plot(
x,
y * 2,
linestyle=":",
color="b",
marker="$\\boxtimes$",
markerfacecolor="b",
markersize="8",
markeredgewidth="0.1",
)
plt.legend(["R", "B"])
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |