如何在 Matplotlib 绘图循环中为标记和线条设置相同的颜色?

matplotlibpythondata visualization更新于 2023/12/3 15:20:00

要在 matplotlib 中为标记和线条设置相同的颜色,我们可以采取以下步骤 −

  • 使用 numpy 初始化 m、nx 数据点。

  • 使用 figure() 方法创建新图形或激活现有图形。

  • 使用 clf() 方法清除图形。

  • 使用 subplot() 方法向当前图形添加子图。

  • 从可迭代标记类型中获取标记。

  • 迭代从 1 到 的范围n。

  • 使用 plot() 方法在循环中绘制线条和标记,每条线的标记和颜色相同。

  • 要显示图形,请使用 show() 方法。

示例

import numpy as np
import itertools
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
m = 5
n = 5
x = np.zeros(shape=(m, n))
plt.figure()
plt.clf()
plt.subplot(111)
marker = itertools.cycle(('o', 'v', '^', '<', '>', 's', '8', 'p'))
for i in range(1, n):
   x = np.dot(i, [1, 1.1, 1.2, 1.3])
   y = x ** 2
   plt.plot(x, y, linestyle='', markeredgecolor='none', marker=next(marker), alpha=1)
   plt.plot(x, y, linestyle='-')
plt.show()

输出


相关文章