我使用 Matplotlib 在图形上绘制线条。现在我想为线上的各个点设置样式,特别是标记。我该怎么做呢?

为了澄清我的问题,我希望能够为一行上的单个标记设置样式,而不是该行上的每个标记。

最佳答案

在您对 linestyle 的调用中指定关键字参数 marker 和/或 plot

例如,使用虚线和蓝色圆圈标记:

plt.plot(range(10), linestyle='--', marker='o', color='b')

对同一件事的快捷调用:
plt.plot(range(10), '--bo')

python - 在 Matplotlib 中为一条线上的各个点设置标记-LMLPHP

以下是可能的线条和标记样式列表:
================    ===============================
character           description
================    ===============================
   -                solid line style
   --               dashed line style
   -.               dash-dot line style
   :                dotted line style
   .                point marker
   ,                pixel marker
   o                circle marker
   v                triangle_down marker
   ^                triangle_up marker
   <                triangle_left marker
   >                triangle_right marker
   1                tri_down marker
   2                tri_up marker
   3                tri_left marker
   4                tri_right marker
   s                square marker
   p                pentagon marker
   *                star marker
   h                hexagon1 marker
   H                hexagon2 marker
   +                plus marker
   x                x marker
   D                diamond marker
   d                thin_diamond marker
   |                vline marker
   _                hline marker
================    ===============================

编辑:以标记任意点子集的示例,如评论中所要求:
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()

python - 在 Matplotlib 中为一条线上的各个点设置标记-LMLPHP

由于 this feature branch 的合并,最后一个使用 markevery kwarg 的示例在 1.4+ 中是可能的。如果您坚持使用旧版本的 matplotlib,您仍然可以通过在线条图上叠加散点图来获得结果。有关更多详细信息,请参阅 edit history

关于python - 在 Matplotlib 中为一条线上的各个点设置标记,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8409095/

10-14 19:33
查看更多