Juh*_*uha 11 python matplotlib legend
我可以访问图形实例fig = pylab.gcf().我知道在这个图中有一个传说,我可以通过它访问它myLegend = fig.gca().legend_.现在我想更改图例的属性.其中一些我可以通过设置者访问myLegend.set_frame_on(True).
创建图例时,它接受许多关键字参数:
class matplotlib.legend.Legend(parent,handles,labels,loc = None,numpoints = None,markerscale = None,scatterpoints = None,scatteryoffsets = None,prop = None,fontsize = None,borderpad = None,labelspacing = None,handlelength = None,handlehepad = None,handletextpad = None,borderaxespad = None,columnspacing = None,ncol = 1,mode = None,fancybox = None,shadow = None,title = None,framealpha = None,bbox_to_anchor = None,bbox_transform = None ,frameon = None,handler_map = None)
创建图例后,如何修改图例中的所有关键字参数?
其中一个有问题的是numpoints(图例中的标记数量,默认值为2).以下是我想要更改它的示例:
这显示了我想如何编程
import pylab
pylab.plot(0,0,'ro', label = 'one point')
pylab.legend(loc = "lower left")
# no modifications above this line
setattr(pylab.gcf().gca().legend_, 'numpoints',1)
pylab.show()
Run Code Online (Sandbox Code Playgroud)
这显示了我希望它看起来像
import pylab
pylab.plot(0,0,'ro', label = 'one point')
pylab.legend(numpoints = 1, loc = "lower left")
pylab.show()
Run Code Online (Sandbox Code Playgroud)
我已经解决了源代码,有一个numpoint变量被更改,但大写不会更新到屏幕.我错过了什么?
我编写了一个函数modify_legend,它在创建图例后对其进行修改。它基本上从已经创建的图例中读取所有参数,使用您提供的键值参数更新它并legend(...)再次使用所有可能的参数调用。
您的问题将通过以下方式解决:
import pylab
pylab.plot(0,0,'ro', label = 'one point')
pylab.legend(loc = "lower left")
modify_legend(numpoints = 1)
pylab.show()
Run Code Online (Sandbox Code Playgroud)
这是代码modify_legend:
def modify_legend(**kwargs):
import matplotlib as mpl
l = mpl.pyplot.gca().legend_
defaults = dict(
loc = l._loc,
numpoints = l.numpoints,
markerscale = l.markerscale,
scatterpoints = l.scatterpoints,
scatteryoffsets = l._scatteryoffsets,
prop = l.prop,
# fontsize = None,
borderpad = l.borderpad,
labelspacing = l.labelspacing,
handlelength = l.handlelength,
handleheight = l.handleheight,
handletextpad = l.handletextpad,
borderaxespad = l.borderaxespad,
columnspacing = l.columnspacing,
ncol = l._ncol,
mode = l._mode,
fancybox = type(l.legendPatch.get_boxstyle())==mpl.patches.BoxStyle.Round,
shadow = l.shadow,
title = l.get_title().get_text() if l._legend_title_box.get_visible() else None,
framealpha = l.get_frame().get_alpha(),
bbox_to_anchor = l.get_bbox_to_anchor()._bbox,
bbox_transform = l.get_bbox_to_anchor()._transform,
frameon = l._drawFrame,
handler_map = l._custom_handler_map,
)
if "fontsize" in kwargs and "prop" not in kwargs:
defaults["prop"].set_size(kwargs["fontsize"])
mpl.pyplot.legend(**dict(defaults.items() + kwargs.items()))
Run Code Online (Sandbox Code Playgroud)
代码注意事项:
Legend对象中读取,其他参数(如title, fancybox)需要一些“艺术”。你可以检查matplotlib.legend.Legend.__init__一下它是如何以及为什么完成的。fontsize当图例最初使用 a 创建时,参数上的额外条件用于覆盖字体大小prop,prop通常会覆盖fontsize。bbox_to_anchor和 -bbox_transform参数),所以请随意尝试并改进代码:)| 归档时间: |
|
| 查看次数: |
4290 次 |
| 最近记录: |