如何在matplotlib中使用单个打印命令打印多条线(相同的数据、不同的样式)?
在我的示例中,我想在实际数据(示例中的蓝色“俯仰角”线)后面绘制一条“突出显示”线(一条黑色的粗线,上面有一条较窄的黄线以创建黑色轮廓) My function如何在matplotlib中使用单个打印命令打印多条线(相同的数据、不同的样式)?,matplotlib,Matplotlib,在我的示例中,我想在实际数据(示例中的蓝色“俯仰角”线)后面绘制一条“突出显示”线(一条黑色的粗线,上面有一条较窄的黄线以创建黑色轮廓) My functionhighlight对pandas系列x中的元素执行此操作,其中h为True,并最终绘制x高亮显示返回创建的高亮显示线的唯一标识符,以及用于编辑图例条目以生成图像中所示内容的实际线样式,但据我所知,在所有打印命令之后,即在高亮显示之外,必须执行此操作,假设将向轴添加其他内容,例如我的示例中的“细螺距”和“10度”线 def highlig
highlight
对pandas系列x
中的元素执行此操作,其中h
为True
,并最终绘制x
<代码>高亮显示返回创建的高亮显示线的唯一标识符,以及用于编辑图例条目以生成图像中所示内容的实际线样式,但据我所知,在所有打印命令之后,即在高亮显示
之外,必须执行此操作,假设将向轴添加其他内容,例如我的示例中的“细螺距”和“10度”线
def highlight(x, h, hlw=8, hc='#FFFBCC', hll='Highlighted', **kwargs):
"""
Plot data in Series x, highlighting the elements correponding to True in h.
"""
# For passing to extra the highlighter lines, drop any passed kwargs which
# would clobber their appearance. Keep a copy of the full set for the data.
# The extra lines are plotted first so they appear underneath the actual
# data.
fullkwargs = kwargs.copy()
for k in ['lw', 'linewidth', 'linestyle', 'ls', 'color', 'c', 'label']:
kwargs.pop(k, None)
# Generate a probably unique ID so that the legend entries of these lines
# can be identified by the caller.
import random
gid = random.random()
# Plot the highlighting lines. First, plot a heavier black line to provide
# a clear outline to the bright highlighted region.
x.where(h).plot(lw=hlw+2, c='k', label='_dont_put_me_in_legend', **kwargs)
# Plot the bright highlighter line on top of that. Give this line an id.
x.where(h).plot(lw=hlw, c=hc, label=hll, gid=gid, **kwargs)
# Plot the actual data.
a = x.plot(**fullkwargs)
# Generate the custom legend entry artists.
import matplotlib.lines as mlines
l1 = mlines.Line2D([], [], lw=hlw+2, c='k')
l2 = mlines.Line2D([], [], lw=hlw, c=hc)
# Return the unique identifier of this call, and the tuple of line styles to
# go to HandlerTuple (see
# http://matplotlib.org/users/legend_guide.html#legend-handlers). This
# makes it possible to update all "highlighter" legend entries with the
# correct color-on-black visual style produced here.
return {gid: (l1, l2)}
我在调用plt.legend()时通过循环所有图例条目并替换图例键(其中,gid
是highlight
返回的值之一),为高亮显示生成准确的图例条目
handles,labels = a.get_legend_handles_labels()
newhandles = []
for h in handles:
if h.get_gid() in hi:
newhandles.append(hi[h.get_gid()])
else:
newhandles.append(h)
a.legend(newhandles, labels)
matplotlib中是否有方法定义“复合”线样式,以便一个打印命令生成所需的外观,并且只有一个图例条目