m0_57503110 2021-04-21 16:14 采纳率: 100%
浏览 173
已采纳

matplotlib画图时出现报错

 画柱状图时,输入代码如下:

%matplotlib inline
from matplotlib.ticker import FuncFormatter

# Plot
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), dpi=120, sharey=True)
# Topic Distribution by Dominant Topics
ax1.bar(x='Dominant_Topic', height='count', data=df_dominant_topic_in_each_doc, width=.5, color='firebrick')
ax1.set_xticks(range(df_dominant_topic_in_each_doc.Dominant_Topic.unique().__len__()))
tick_formatter = FuncFormatter(lambda x, pos: 'Topic ' + str(x)+ '\n' + df_top3words.loc[df_top3words.topic_id==x, 'words'].values[0])
ax1.xaxis.set_major_formatter(tick_formatter)
ax1.set_title('Number of Documents by Dominant Topic', fontdict=dict(size=10))
ax1.set_ylabel('Number of Documents')
ax1.set_ylim(0, 1000)
# Topic Distribution by Topic Weights
ax2.bar(x='index', height='count', data=df_topic_weightage_by_doc, width=.5, color='steelblue')
ax2.set_xticks(range(df_topic_weightage_by_doc.index.unique().__len__()))
ax2.xaxis.set_major_formatter(tick_formatter)
ax2.set_title('Number of Documents by Topic Weightage', fontdict=dict(size=10))

plt.show()

 分行输入时,显示报错代码是它:

ax1.xaxis.set_major_formatter(tick_formatter)

报错代码如下:

IndexError                                Traceback (most recent call last)
D:\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

D:\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

D:\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

D:\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2228                        else suppress())
   2229                 with ctx:
-> 2230                     self.figure.draw(renderer)
   2231 
   2232             if bbox_inches:

D:\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     72     @wraps(draw)
     73     def draw_wrapper(artist, renderer, *args, **kwargs):
---> 74         result = draw(artist, renderer, *args, **kwargs)
     75         if renderer._rasterizing:
     76             renderer.stop_rasterizing()

D:\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

D:\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   2735 
   2736             self.patch.draw(renderer)
-> 2737             mimage._draw_list_compositing_images(
   2738                 renderer, self, artists, self.suppressComposite)
   2739 

D:\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    130     if not_composite or not has_images:
    131         for a in artists:
--> 132             a.draw(renderer)
    133     else:
    134         # Composite any adjacent images together

D:\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

D:\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*inner_args, **inner_kwargs)
    429                          else deprecation_addendum,
    430                 **kwargs)
--> 431         return func(*inner_args, **inner_kwargs)
    432 
    433     return wrapper

D:\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2923             renderer.stop_rasterizing()
   2924 
-> 2925         mimage._draw_list_compositing_images(renderer, self, artists)
   2926 
   2927         renderer.close_group('axes')

D:\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    130     if not_composite or not has_images:
    131         for a in artists:
--> 132             a.draw(renderer)
    133     else:
    134         # Composite any adjacent images together

D:\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

D:\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1128         renderer.open_group(__name__, gid=self.get_gid())
   1129 
-> 1130         ticks_to_draw = self._update_ticks()
   1131         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1132                                                                 renderer)

D:\lib\site-packages\matplotlib\axis.py in _update_ticks(self)
   1016         """
   1017         major_locs = self.get_majorticklocs()
-> 1018         major_labels = self.major.formatter.format_ticks(major_locs)
   1019         major_ticks = self.get_major_ticks(len(major_locs))
   1020         self.major.formatter.set_locs(major_locs)

D:\lib\site-packages\matplotlib\ticker.py in format_ticks(self, values)
    261         """Return the tick labels for all the ticks at once."""
    262         self.set_locs(values)
--> 263         return [self(value, i) for i, value in enumerate(values)]
    264 
    265     def format_data(self, value):

D:\lib\site-packages\matplotlib\ticker.py in <listcomp>(.0)
    261         """Return the tick labels for all the ticks at once."""
    262         self.set_locs(values)
--> 263         return [self(value, i) for i, value in enumerate(values)]
    264 
    265     def format_data(self, value):

D:\lib\site-packages\matplotlib\ticker.py in __call__(self, x, pos)
    397         *x* and *pos* are passed through as-is.
    398         """
--> 399         return self.func(x, pos)
    400 
    401     def get_offset(self):

<ipython-input-40-3fd23decafbb> in <lambda>(x, pos)
      7 ax1.bar(x='Dominant_Topic', height='count', data=df_dominant_topic_in_each_doc, width=.5, color='firebrick')
      8 ax1.set_xticks(range(df_dominant_topic_in_each_doc.Dominant_Topic.unique().__len__()))
----> 9 tick_formatter = FuncFormatter(lambda x, pos: 'Topic ' + str(x)+ '\n' + df_top3words.loc[df_top3words.topic_id==x, 'words'].values[0])
     10 ax1.xaxis.set_major_formatter(tick_formatter)
     11 ax1.set_title('Number of Documents by Dominant Topic', fontdict=dict(size=10))

IndexError: index 0 is out of bounds for axis 0 with size 0

<Figure size 1200x480 with 2 Axes>

 

  • 写回答

3条回答 默认 最新

  • CSDN专家-HGJ 2021-04-21 16:26
    关注

    错误是索引超出范围。是因为loc[df_top3words.topic_id==x, 'words']语法不对导致的错误,这样写行标签是一个bool值,当然取不到元素,应该是loc[x, 'words']定位行标签为x,列标签为'words'的元素。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?