2

I'm trying to format the yaxis on a matplotlib graph using set_major_formatter. The plot is generated correctly, but the ax.yaxis.set_major_formatter() throws a couple of weird errors.

The formatter:

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

The code that uses the formatter:

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

Error:

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

Am I doing something wrong or is this a bug?

4

1 に答える 1

8

The error is because set_major_formatter assumes it is getting a Formatter object (doc) so it is blowing up when it tries to do stuff with your function.

I think you are looking for either FormatStrFormatter or FuncFormatter. (doc)

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

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

The second argument in the signature is mandatory.

or (which doesn't do what you want, but is closely related)

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