在我的例子中,我想在实际数据后面绘制一条“突出显示”线(一条黑色粗线,上面有一条较窄的黄线,以创建一个黑色轮廓)(在我的例子中为蓝色'Pitch Angle'线)
我的函数highlight
为pandas系列x
中的元素执行此操作,h
为True
,最后绘制x
。 highlight
返回创建的突出显示行的唯一标识符,以及用于允许编辑图例条目以生成您在图像中看到的内容的实际线条样式,但据我所知,这毕竟必须完成绘制命令,即在highlight
之外,假设其他东西将被添加到轴中,例如在我的例子中,“精细音高”和“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)}
我设法通过循环遍历所有图例条目并替换其中gid
是其中之一的图例键来调用plt.legend()时,通过使用HandlerTuple来生成突出显示的精确图例条目。 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中是否有办法定义“复合”线条样式,以便一个绘图命令生成所需的外观并且只有一个图例条目?