我想使用红色和绿色来区分正数和负数,这将在一张照片中使用abs(num)。我在网上搜索并找到一些方法来处理它。但结果是错误的。我粘贴代码并希望某人。帮助。
" df_combine"像这样的文件:
t o h l c nu octime ocsize cum_size
0 2017-07-02 22:01:00 1241.65 1241.85 1241.63 1241.85 0 2017-07-02 22:01:32 32 32
1 2017-07-02 22:02:00 1241.95 1241.95 1241.85 1241.95 0 2017-07-02 22:02:00 -24 12
2 2017-07-02 22:03:00 1242.05 1242.15 1242.05 1242.15 0 2017-07-02 22:03:00 -48 -36
3 2017-07-02 22:04:00 1242.25 1242.25 1242.16 1242.17 0 2017-07-02 22:04:00 -100 -136
4 2017-07-02 22:05:00 1242.16 1242.57 1241.85 1242.57 0 2017-07-02 22:05:00 200 64
holding_info文件如下:
cum_size factor
0 32.0 True
1 12.0 True
2 -36.0 False
3 -136.0 False
4 64.0 True
像这样的代码:
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
t=df_combine.iloc[:,0]
o=df_combine.iloc[:,1]
h=df_combine.iloc[:,2]
l=df_combine.iloc[:,3]
c=df_combine.iloc[:,4]
holding_octime=df_combine['t']
holding_size=df_combine['cum_size'] ##df_cumbine is a DataFrame
holding_info=pd.Series.to_frame(holding_size)
holding_info['factor']=holding_info['cum_size']>0
fig,ax1=plt.subplots()
ax1.plot_date(t,o,linestyle='--',color='b',marker='D',alpha=0.6) ##t,o,h,l,c are pd.Series which contains time and price
ax1.plot_date(t,c,linestyle='--',color='k',marker='D',alpha=0.6)
ax1.plot_date(t,h,color='g',marker='^',alpha=0.3)
ax1.plot_date(t,l,color='r',marker='v',alpha=0.3)
ax2=ax1.twinx()
ax2.plot_date(holding_octime,abs(holding_size),color=holding_info.factor.map({True:'r', False:'k'})) ##octime is a pd.Series which contains time
dformat=mpl.dates.DateFormatter('%Y.%m.%d %H:%M')
ax1.xaxis.set_major_formatter(dformat)
fig.autofmt_xdate()
plt.show()
找到这样的错误:
> ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
C:\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:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
238
239 if 'png' in formats:
--> 240 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
241 if 'retina' in formats or 'png2x' in formats:
242 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
C:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
122
123 bytes_io = BytesIO()
--> 124 fig.canvas.print_figure(bytes_io, **kw)
125 data = bytes_io.getvalue()
126 if fmt == 'svg':
C:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
2198 orientation=orientation,
2199 dryrun=True,
-> 2200 **kwargs)
2201 renderer = self.figure._cachedRenderer
2202 bbox_inches = self.figure.get_tightbbox(renderer)
C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
543
544 def print_png(self, filename_or_obj, *args, **kwargs):
--> 545 FigureCanvasAgg.draw(self)
546 renderer = self.get_renderer()
547 original_dpi = renderer.dpi
C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
462
463 try:
--> 464 self.figure.draw(self.renderer)
465 finally:
466 RendererAgg.lock.release()
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
61 def draw_wrapper(artist, renderer, *args, **kwargs):
62 before(artist, renderer)
---> 63 draw(artist, renderer, *args, **kwargs)
64 after(artist, renderer)
65
C:\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
1142
1143 mimage._draw_list_compositing_images(
-> 1144 renderer, self, dsu, self.suppressComposite)
1145
1146 renderer.close_group('figure')
C:\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
137 if not_composite or not has_images:
138 for zorder, a in dsu:
--> 139 a.draw(renderer)
140 else:
141 # Composite any adjacent images together
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
61 def draw_wrapper(artist, renderer, *args, **kwargs):
62 before(artist, renderer)
---> 63 draw(artist, renderer, *args, **kwargs)
64 after(artist, renderer)
65
C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
2424 renderer.stop_rasterizing()
2425
-> 2426 mimage._draw_list_compositing_images(renderer, self, dsu)
2427
2428 renderer.close_group('axes')
C:\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
137 if not_composite or not has_images:
138 for zorder, a in dsu:
--> 139 a.draw(renderer)
140 else:
141 # Composite any adjacent images together
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
61 def draw_wrapper(artist, renderer, *args, **kwargs):
62 before(artist, renderer)
---> 63 draw(artist, renderer, *args, **kwargs)
64 after(artist, renderer)
65
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in draw(self, renderer)
826 gc = renderer.new_gc()
827 self._set_gc_clip(gc)
--> 828 rgbaFace = self._get_rgba_face()
829 rgbaFaceAlt = self._get_rgba_face(alt=True)
830 edgecolor = self.get_markeredgecolor()
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in _get_rgba_face(self, alt)
1335 def _get_rgba_face(self, alt=False):
1336 facecolor = self._get_markerfacecolor(alt=alt)
-> 1337 if is_string_like(facecolor) and facecolor.lower() == 'none':
1338 rgbaFace = None
1339 else:
C:\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
2968 if name in self._info_axis:
2969 return self[name]
-> 2970 return object.__getattribute__(self, name)
2971
2972 def __setattr__(self, name, value):
AttributeError: 'Series' object has no attribute 'lower'
<matplotlib.figure.Figure at 0x9db80b8>
我从另一个案例中研究代码。如果我使用ax1.plot而不是ax1.plot_date,则错误信息将更改为:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
140 try:
--> 141 rgba = _colors_full_map.cache[c, alpha]
142 except (KeyError, TypeError): # Not in cache, or unhashable.
C:\Anaconda3\lib\site-packages\pandas\core\generic.py in __hash__(self)
830 raise TypeError('{0!r} objects are mutable, thus they cannot be'
--> 831 ' hashed'.format(self.__class__.__name__))
832
TypeError: 'Series' objects are mutable, thus they cannot be hashed
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
C:\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:\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:\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:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
2190 orientation=orientation,
2191 dryrun=True,
-> 2192 **kwargs)
2193 renderer = self.figure._cachedRenderer
2194 bbox_inches = self.figure.get_tightbbox(renderer)
C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
543
544 def print_png(self, filename_or_obj, *args, **kwargs):
--> 545 FigureCanvasAgg.draw(self)
546 renderer = self.get_renderer()
547 original_dpi = renderer.dpi
C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
462
463 try:
--> 464 self.figure.draw(self.renderer)
465 finally:
466 RendererAgg.lock.release()
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,
renderer, *args, **kwargs)
61 def draw_wrapper(artist, renderer, *args, **kwargs):
62 before(artist, renderer)
---> 63 draw(artist, renderer, *args, **kwargs)
64 after(artist, renderer)
65
C:\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
1141
1142 mimage._draw_list_compositing_images(
-> 1143 renderer, self, dsu, self.suppressComposite)
1144
1145 renderer.close_group('figure')
C:\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
137 if not_composite or not has_images:
138 for zorder, a in dsu:
--> 139 a.draw(renderer)
140 else:
141 # Composite any adjacent images together
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
61 def draw_wrapper(artist, renderer, *args, **kwargs):
62 before(artist, renderer)
---> 63 draw(artist, renderer, *args, **kwargs)
64 after(artist, renderer)
65
C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
2407 renderer.stop_rasterizing()
2408
-> 2409 mimage._draw_list_compositing_images(renderer, self, dsu)
2410
2411 renderer.close_group('axes')
C:\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
137 if not_composite or not has_images:
138 for zorder, a in dsu:
--> 139 a.draw(renderer)
140 else:
141 # Composite any adjacent images together
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
61 def draw_wrapper(artist, renderer, *args, **kwargs):
62 before(artist, renderer)
---> 63 draw(artist, renderer, *args, **kwargs)
64 after(artist, renderer)
65
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in draw(self, renderer)
801 self._set_gc_clip(gc)
802
--> 803 ln_color_rgba = self._get_rgba_ln_color()
804 gc.set_foreground(ln_color_rgba, isRGBA=True)
805 gc.set_alpha(ln_color_rgba[3])
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in _get_rgba_ln_color(self, alt)
1342
1343 def _get_rgba_ln_color(self, alt=False):
-> 1344 return mcolors.to_rgba(self._color, self._alpha)
1345
1346 # some aliases....
C:\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
141 rgba = _colors_full_map.cache[c, alpha]
142 except (KeyError, TypeError): # Not in cache, or unhashable.
--> 143 rgba = _to_rgba_no_colorcycle(c, alpha)
144 try:
145 _colors_full_map.cache[c, alpha] = rgba
C:\Anaconda3\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
190 # not numpy floats.
191 try:
--> 192 c = tuple(map(float, c))
193 except TypeError:
194 raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
ValueError: could not convert string to float: 'k'
<matplotlib.figure.Figure at 0x263096fa128>
为什么会这样?
我真正要做的是在同一张图片中制作一张有关体积大小和地块价格的条形图 要么 如果尺寸> n(linspace可能是50,100,200),则在不同颜色的几个时间范围内制作整个背景。比如在2017-8-19 08:20:10和2017-8-19 08:30:20之间,尺寸= 70,然后使用黄色填充此范围背景。并在2017-8-20 08:20:10之间2017-8-20 08:30:20,尺寸= 150,然后使用红色填充此范围背景。
只是解决一个问题是好的,有些想法不能一时解决:)