Matplotlib:如何更改颜色,创建小间距并编辑图例

3

我有如下代码用于在matplotlib中绘制线条。我试图使用透明的圆圈来显示点,而不是标准的实心填充圆圈。

  1. How can I make the circles be the same color as the lines?
  2. How can I remove the circles from the ends of the dashed lines in the legend? Currently you can hardly see the dashed lines.
  3. How can I make a little gap before and after each circle in the graph so the dashed lines don't touch them. I think this would look better here as I only have data at the points so the lines in between don't represent real data.

    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()
    

这是目前matplotlib代码给我的结果。

enter image description here

这是我希望最终看起来像的样子(当然,数据不同)。

enter image description here

2个回答

5
请注意,您似乎在调用plot时误用了fmt格式字符串(如“-go”)。 实际上,对于虚线,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()

在此输入图片描述

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


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')

关于第三个问题,我不知道。我认为没有一种简单的方法可以做到这一点。但是我猜你可以按照以下步骤操作:
  1. 绘制线条
  2. 绘制实心白色标记,比现有标记略大(边缘和面颜色为白色)。这些标记将掩盖真实标记周围的部分。
  3. 使用所需颜色绘制真实标记。

感谢您解决了第一个问题! - Simd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接