2

我正在尝试使用 set_major_formatter 在 matplotlib 图上格式化 y 轴。该图生成正确,但 ax.yaxis.set_major_formatter() 引发了一些奇怪的错误。

格式化程序:

def mjrFormatter(x):
    return "{0:.0f}%".format(x * 100)

使用格式化程序的代码:

 ...
 ax.yaxis.set_major_formatter(mjrFormatter)
 ...

错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-108-b436fe657a8b> in <module>()
----> 1 plot_func(data = data, figsize=(20,10), fig_title = 'title')

<ipython-input-107-d60ffc010a75> in plot_percent_moc(data, figsize, fig_title)
     16         _ = data2[col].plot()
     17 
---> 18     ax.yaxis.set_major_formatter(mjrFormatter)
     19 
     20     fig.suptitle(fig_title, fontsize = 14)

C:\Python27\lib\site-packages\matplotlib\axis.pyc in set_major_formatter(self, formatter)
   1396         self.isDefault_majfmt = False
   1397         self.major.formatter = formatter
-> 1398         formatter.set_axis(self)
   1399 
   1400     def set_minor_formatter(self, formatter):

AttributeError: 'function' object has no attribute 'set_axis'

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\Python27\lib\site-packages\IPython\zmq\pylab\backend_inline.pyc in show(close)
    100     try:
    101         for figure_manager in Gcf.get_all_fig_managers():
--> 102             send_figure(figure_manager.canvas.figure)
    103     finally:
    104         show._to_draw = []

C:\Python27\lib\site-packages\IPython\zmq\pylab\backend_inline.pyc in send_figure(fig)
    209     """
    210     fmt = InlineBackend.instance().figure_format
--> 211     data = print_figure(fig, fmt)
    212     # print_figure will return None if there's nothing to draw:
    213     if data is None:

C:\Python27\lib\site-packages\IPython\core\pylabtools.pyc in print_figure(fig, fmt)
    102     try:
    103         bytes_io = BytesIO()
--> 104         fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight')
    105         data = bytes_io.getvalue()
    106     finally:

C:\Python27\lib\site-packages\matplotlib\backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2050                     orientation=orientation,
   2051                     dryrun=True,
-> 2052                     **kwargs)
   2053                 renderer = self.figure._cachedRenderer
   2054                 bbox_inches = self.figure.get_tightbbox(renderer)

C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
    489 
    490     def print_png(self, filename_or_obj, *args, **kwargs):
--> 491         FigureCanvasAgg.draw(self)
    492         renderer = self.get_renderer()
    493         original_dpi = renderer.dpi

C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.pyc in draw(self)
    437 
    438         try:
--> 439             self.figure.draw(self.renderer)
    440         finally:
    441             RendererAgg.lock.release()

C:\Python27\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     52     def draw_wrapper(artist, renderer, *args, **kwargs):
     53         before(artist, renderer)
---> 54         draw(artist, renderer, *args, **kwargs)
     55         after(artist, renderer)
     56 

C:\Python27\lib\site-packages\matplotlib\figure.pyc in draw(self, renderer)
    997         dsu.sort(key=itemgetter(0))
    998         for zorder, a, func, args in dsu:
--> 999             func(*args)
   1000 
   1001         renderer.close_group('figure')

C:\Python27\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     52     def draw_wrapper(artist, renderer, *args, **kwargs):
     53         before(artist, renderer)
---> 54         draw(artist, renderer, *args, **kwargs)
     55         after(artist, renderer)
     56 

C:\Python27\lib\site-packages\matplotlib\axes.pyc in draw(self, renderer, inframe)
   2084 
   2085         for zorder, a in dsu:
-> 2086             a.draw(renderer)
   2087 
   2088         renderer.close_group('axes')

C:\Python27\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     52     def draw_wrapper(artist, renderer, *args, **kwargs):
     53         before(artist, renderer)
---> 54         draw(artist, renderer, *args, **kwargs)
     55         after(artist, renderer)
     56 

C:\Python27\lib\site-packages\matplotlib\axis.pyc in draw(self, renderer, *args, **kwargs)
   1046         renderer.open_group(__name__)
   1047 
-> 1048         ticks_to_draw = self._update_ticks(renderer)
   1049         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1050                                                                 renderer)

C:\Python27\lib\site-packages\matplotlib\axis.pyc in _update_ticks(self, renderer)
    933 
    934         interval = self.get_view_interval()
--> 935         tick_tups = [t for t in self.iter_ticks()]
    936         if self._smart_bounds:
    937             # handle inverted limits

C:\Python27\lib\site-packages\matplotlib\axis.pyc in iter_ticks(self)
    879         majorLocs = self.major.locator()
    880         majorTicks = self.get_major_ticks(len(majorLocs))
--> 881         self.major.formatter.set_locs(majorLocs)
    882         majorLabels = [self.major.formatter(val, i)
    883                        for i, val in enumerate(majorLocs)]

AttributeError: 'function' object has no attribute 'set_locs'

我做错了什么还是这是一个错误?

4

1 回答 1

8

该错误是因为set_major_formatter假设它正在获取一个Formatter对象(doc),因此当它尝试对您的函数做一些事情时它会爆炸。

我认为您正在寻找FormatStrFormatterFuncFormatter。(文档

def mjrFormatter(x, pos):
    return "{0:.0f}%".format(x * 100)

gca().yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))

签名中的第二个参数是强制性的。

或(不符合您的要求,但密切相关)

gca().yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.2f%%'))
于 2013-02-06T15:34:47.150 回答