问题是使用循环绘制Seaborn和Matplotlib数字

时间:2017-04-19 14:39:47

标签: python-3.x matplotlib seaborn

我在保存一系列两个Seaborn小提琴图和一个普通的matplotlib图时遇到了一些麻烦,每次我的代码遍历一个循环时都会运行。

我的代码是:

for symbol in symbol_list:

    <DO SOMETHING - CREATE PANDAS DATAFRAME NAMED "df">

    img = sns.violinplot(x=df['Onside'].dropna().astype(float))
    fig = img.get_figure()
    fig.savefig(symbol+" Onside Violin Plot.png")
    fig.clf()

    sns.violinplot(x=df['Offside'].dropna().astype(float))
    fig = img.get_figure()

    fig.savefig(symbol+" Offside Violin Plot.png")
    fig.clf()


    plt.figure(1)
    plt.subplot(211)
    plt.hist(df['Onside'],bins=50,alpha=0.5,label="Onside")
    plt.hist(df['Offside'],bins=50,alpha=0.5,label="Offside")
    plt.legend(loc='best')
    plt.xlabel("Pips")
    plt.ylabel("Number of Trades")

    plt.subplot(212)
    plt.bar(df.index,df['Offside'],color='r',width=0.5)
    plt.bar(df.index,df['Onside'],color='blue',width=0.5)
    plt.savefig(symbol+'_Onside_Offside')
    plt.plot()

它在循环的第一次迭代中正确运行但在第二次循环时我收到以下错误消息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-269b21e53a2f> in <module>()
    112     img = sns.violinplot(x=df['Onside'].dropna().astype(float))#.figure.savefig(symbol+" Onside Violin Plot.png")
    113     fig = img.get_figure()
--> 114     fig.savefig(symbol+" Onside Violin Plot.png")
    115     fig.clf()
    116 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\figure.py in savefig(self, *args, **kwargs)
   1561             self.set_frameon(frameon)
   1562 
-> 1563         self.canvas.print_figure(*args, **kwargs)
   1564 
   1565         if frameon:

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2230                 orientation=orientation,
   2231                 bbox_inches_restore=_bbox_inches_restore,
-> 2232                 **kwargs)
   2233         finally:
   2234             if bbox_inches and restore_bbox:

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    525 
    526     def print_png(self, filename_or_obj, *args, **kwargs):
--> 527         FigureCanvasAgg.draw(self)
    528         renderer = self.get_renderer()
    529         original_dpi = renderer.dpi

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    472 
    473         try:
--> 474             self.figure.draw(self.renderer)
    475         finally:
    476             RendererAgg.lock.release()

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     60     def draw_wrapper(artist, renderer, *args, **kwargs):
     61         before(artist, renderer)
---> 62         draw(artist, renderer, *args, **kwargs)
     63         after(artist, renderer)
     64 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1157         dsu.sort(key=itemgetter(0))
   1158         for zorder, a, func, args in dsu:
-> 1159             func(*args)
   1160 
   1161         renderer.close_group('figure')

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     60     def draw_wrapper(artist, renderer, *args, **kwargs):
     61         before(artist, renderer)
---> 62         draw(artist, renderer, *args, **kwargs)
     63         after(artist, renderer)
     64 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2317 
   2318         for zorder, a in dsu:
-> 2319             a.draw(renderer)
   2320 
   2321         renderer.close_group('axes')

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     60     def draw_wrapper(artist, renderer, *args, **kwargs):
     61         before(artist, renderer)
---> 62         draw(artist, renderer, *args, **kwargs)
     63         after(artist, renderer)
     64 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1106         renderer.open_group(__name__)
   1107 
-> 1108         ticks_to_draw = self._update_ticks(renderer)
   1109         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1110                                                                 renderer)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in _update_ticks(self, renderer)
    949 
    950         interval = self.get_view_interval()
--> 951         tick_tups = [t for t in self.iter_ticks()]
    952         if self._smart_bounds:
    953             # handle inverted limits

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in <listcomp>(.0)
    949 
    950         interval = self.get_view_interval()
--> 951         tick_tups = [t for t in self.iter_ticks()]
    952         if self._smart_bounds:
    953             # handle inverted limits

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in iter_ticks(self)
    892         Iterate through all of the major and minor ticks.
    893         """
--> 894         majorLocs = self.major.locator()
    895         majorTicks = self.get_major_ticks(len(majorLocs))
    896         self.major.formatter.set_locs(majorLocs)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in __call__(self)
   1005     def __call__(self):
   1006         'Return the locations of the ticks'
-> 1007         self.refresh()
   1008         return self._locator()
   1009 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in refresh(self)
   1025     def refresh(self):
   1026         'Refresh internal information based on current limits.'
-> 1027         dmin, dmax = self.viewlim_to_dt()
   1028         self._locator = self.get_locator(dmin, dmax)
   1029 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in viewlim_to_dt(self)
    769             vmin, vmax = vmax, vmin
    770 
--> 771         return num2date(vmin, self.tz), num2date(vmax, self.tz)
    772 
    773     def _get_unit(self):

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in num2date(x, tz)
    417         tz = _get_rc_timezone()
    418     if not cbook.iterable(x):
--> 419         return _from_ordinalf(x, tz)
    420     else:
    421         x = np.asarray(x)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in _from_ordinalf(x, tz)
    269 
    270     ix = int(x)
--> 271     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    272 
    273     remainder = float(x) - ix

ValueError: ordinal must be >= 1

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    305                 pass
    306             else:
--> 307                 return printer(obj)
    308             # Finally look for special method names
    309             method = get_real_method(obj, self.print_method)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    225 
    226     if 'png' in formats:
--> 227         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    228     if 'retina' in formats or 'png2x' in formats:
    229         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    117 
    118     bytes_io = BytesIO()
--> 119     fig.canvas.print_figure(bytes_io, **kw)
    120     data = bytes_io.getvalue()
    121     if fmt == 'svg':

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2178                     orientation=orientation,
   2179                     dryrun=True,
-> 2180                     **kwargs)
   2181                 renderer = self.figure._cachedRenderer
   2182                 bbox_inches = self.figure.get_tightbbox(renderer)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    525 
    526     def print_png(self, filename_or_obj, *args, **kwargs):
--> 527         FigureCanvasAgg.draw(self)
    528         renderer = self.get_renderer()
    529         original_dpi = renderer.dpi

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    472 
    473         try:
--> 474             self.figure.draw(self.renderer)
    475         finally:
    476             RendererAgg.lock.release()

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     60     def draw_wrapper(artist, renderer, *args, **kwargs):
     61         before(artist, renderer)
---> 62         draw(artist, renderer, *args, **kwargs)
     63         after(artist, renderer)
     64 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1157         dsu.sort(key=itemgetter(0))
   1158         for zorder, a, func, args in dsu:
-> 1159             func(*args)
   1160 
   1161         renderer.close_group('figure')

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     60     def draw_wrapper(artist, renderer, *args, **kwargs):
     61         before(artist, renderer)
---> 62         draw(artist, renderer, *args, **kwargs)
     63         after(artist, renderer)
     64 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2317 
   2318         for zorder, a in dsu:
-> 2319             a.draw(renderer)
   2320 
   2321         renderer.close_group('axes')

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     60     def draw_wrapper(artist, renderer, *args, **kwargs):
     61         before(artist, renderer)
---> 62         draw(artist, renderer, *args, **kwargs)
     63         after(artist, renderer)
     64 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1106         renderer.open_group(__name__)
   1107 
-> 1108         ticks_to_draw = self._update_ticks(renderer)
   1109         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1110                                                                 renderer)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in _update_ticks(self, renderer)
    949 
    950         interval = self.get_view_interval()
--> 951         tick_tups = [t for t in self.iter_ticks()]
    952         if self._smart_bounds:
    953             # handle inverted limits

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in <listcomp>(.0)
    949 
    950         interval = self.get_view_interval()
--> 951         tick_tups = [t for t in self.iter_ticks()]
    952         if self._smart_bounds:
    953             # handle inverted limits

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axis.py in iter_ticks(self)
    892         Iterate through all of the major and minor ticks.
    893         """
--> 894         majorLocs = self.major.locator()
    895         majorTicks = self.get_major_ticks(len(majorLocs))
    896         self.major.formatter.set_locs(majorLocs)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in __call__(self)
   1005     def __call__(self):
   1006         'Return the locations of the ticks'
-> 1007         self.refresh()
   1008         return self._locator()
   1009 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in refresh(self)
   1025     def refresh(self):
   1026         'Refresh internal information based on current limits.'
-> 1027         dmin, dmax = self.viewlim_to_dt()
   1028         self._locator = self.get_locator(dmin, dmax)
   1029 

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in viewlim_to_dt(self)
    769             vmin, vmax = vmax, vmin
    770 
--> 771         return num2date(vmin, self.tz), num2date(vmax, self.tz)
    772 
    773     def _get_unit(self):

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in num2date(x, tz)
    417         tz = _get_rc_timezone()
    418     if not cbook.iterable(x):
--> 419         return _from_ordinalf(x, tz)
    420     else:
    421         x = np.asarray(x)

C:\Users\stuart.jamieson\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\dates.py in _from_ordinalf(x, tz)
    269 
    270     ix = int(x)
--> 271     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    272 
    273     remainder = float(x) - ix

ValueError: ordinal must be >= 1

有人可以指出我哪里出错吗?

我认为这与“plt”数字没有被正确清除有关,因此代码试图在同一图的x轴上绘制两个不同的索引,因此“序数必须> = 1”错误。

我在正确的球场吗?

1 个答案:

答案 0 :(得分:1)

你需要在循环中首先清除图形,否则新内容将绘制到上一循环步骤中的旧图形。

所以你可以添加

plt.gcf().clf()

在循环开始时。