matplotlib:如何更改颜色,创建小空格和编辑图例

时间:2014-12-03 12:17:27

标签: python matplotlib

我有以下代码在matplotlib中绘制一些代码。我试图用透明圆圈显示点,而不是用圆圈填充的标准实体。

  1. 如何使圆圈与线条颜色相同?
  2. 如何从图例中的虚线末端删除圆圈?目前你几乎看不到虚线。
  3. 如何在图表中的每个圆圈之前和之后留出一点间隙,这样虚线就不会碰到它们。我认为这样看起来会更好,因为我只有点数据,所以两者之间的线不代表真实数据。

    import matplotlib.pyplot as plt
    import numpy as np
    t = np.array([0.19641715476064042,
    0.25,
    0.34,
    0.42])
    
    c  = np.array([0.17,
    0.21,
    0.27,
    0.36])
    
    plt.plot(t, '-go', markerfacecolor='w', linestyle= 'dashed', label='n=20')
    plt.plot(c, '-bo',  markerfacecolor='w', linestyle= 'dashed', label='n=22') 
    plt.show()
    
  4. 这就是matplotlib代码目前给我的。

    enter image description here

    我希望它最终看起来像(显然有不同的数据)。

    enter image description here

2 个答案:

答案 0 :(得分:4)

请注意,您在调用"-go"时似乎滥用了 fmt 格式字符串(例如plot)。事实上,对于虚线 fmt 应该更像"--go"。 我个人倾向于发现关键字参数的使用更清晰,即使更详细(在您的情况下,linestyle="dashed"优先于 fmt 字符串)

http://matplotlib.org/api/axes_api.html?highlight=plot#matplotlib.axes.Axes.plot

无论如何,在试验性的下面再现所需的情节:

import matplotlib.pyplot as plt
import numpy as np

t = np.array([0.19641715476064042,
              0.25, 0.34, 0.42])
c = np.array([0.17, 0.21, 0.27, 0.36])

def my_plot(ax, tab, c="g", ls="-", marker="o", ms=6, mfc="w", mec="g", label="",
            zorder=2):
    """
    tab: array to plot
    c: line color (default green)
    ls: linestyle (default solid line)
    marker: kind of marker
    ms: markersize
    mfc: marker face color
    mec: marker edge color
    label: legend label
    """
    ax.plot(tab, c=c, ms=0, ls=ls, label=label, zorder=zorder-0.02)
    ax.plot(tab, c=c, marker=marker, ms=ms, mec=mec, mfc=mfc, ls="none",
            zorder=zorder)
    ax.plot(tab, c=c, marker=marker, ms=ms*4, mfc="w", mec="w", ls="none",
            zorder=zorder-0.01)


my_plot(plt, t, c="g", mec="g", ls="dashed", label="n=20")
my_plot(plt, c, c="b", mec="b", ls="dashed", label="n=22")

plt.legend(loc=2) 
plt.show()

enter image description here

另请考虑阅读官方文档中的图例指南http://matplotlib.org/users/legend_guide.html?highlight=legend%20guide

答案 1 :(得分:1)

对于第一个问题,您使用markeredgecolor属性:

plt.plot(t, '-go', markerfacecolor='w', markeredgecolor='g', linestyle= 'dotted', label='n=20')
plt.plot(c, '-bo', markerfacecolor='w', markeredgecolor='b', linestyle= 'dotted', label='n=22')

至于第三个问题,我不知道。我认为没有一种 easy 方法可以做到这一点。但我想你可以做一下这样的事情:

  1. 绘制线
  2. 绘制比现在略大的纯白色标记(边缘和面部颜色为白色)。这些将掩盖真实标记周围的部分线。
  3. 使用所需颜色绘制真实标记。