The following code, which is run in the jupyter notebook, is giving me a static image:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib nbagg
mat = np.random.random((1000, 50, 50))
def quick_play(dT = 10):
fig, ax = plt.subplots()
im = ax.imshow(mat[0], cmap = "gray")
def init():
im.set_data([])
return im
def animate(i):
im.set_data(mat[i])
return im
ani = animation.FuncAnimation(fig, animate, frames = 100, init_func = init, interval = dT, blit = True)
plt.show()
quick_play()
The output looks like this:
Why is this occuring? Furthermore, when I remove the "%matplotlib nbagg", I get an error message:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-728862430f94> in <module>()
20 plt.show()
21
---> 22 quick_play()
<ipython-input-1-728862430f94> in quick_play(dT)
17 return im
18
---> 19 ani = animation.FuncAnimation(fig, animate, frames = 100, init_func = init, interval = dT, blit = True)
20 plt.show()
21
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in __init__(self, fig, func, frames, init_func, fargs, save_count, **kwargs)
1191 self._save_seq = []
1192
-> 1193 TimedAnimation.__init__(self, fig, **kwargs)
1194
1195 # Need to reset the saved seq, since right now it will contain data
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in __init__(self, fig, interval, repeat_delay, repeat, event_source, *args, **kwargs)
1035
1036 Animation.__init__(self, fig, event_source=event_source,
-> 1037 *args, **kwargs)
1038
1039 def _step(self, *args):
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in __init__(self, fig, event_source, blit)
647 self._stop)
648 if self._blit:
--> 649 self._setup_blit()
650
651 def _start(self, *args):
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in _setup_blit(self)
933 self._resize_id = self._fig.canvas.mpl_connect('resize_event',
934 self._handle_resize)
--> 935 self._post_draw(None, self._blit)
936
937 def _handle_resize(self, *args):
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in _post_draw(self, framedata, blit)
898 self._blit_draw(self._drawn_artists, self._blit_cache)
899 else:
--> 900 self._fig.canvas.draw_idle()
901
902 # The rest of the code in this class is to facilitate easy blitting
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in draw_idle(self, *args, **kwargs)
2024 if not self._is_idle_drawing:
2025 with self._idle_draw_cntx():
-> 2026 self.draw(*args, **kwargs)
2027
2028 def draw_cursor(self, event):
C:\Users\Alexander\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\Alexander\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\Alexander\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
1163
1164 self._cachedRenderer = renderer
-> 1165 self.canvas.draw_event(renderer)
1166
1167 def draw_artist(self, a):
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in draw_event(self, renderer)
1807 s = 'draw_event'
1808 event = DrawEvent(s, self, renderer)
-> 1809 self.callbacks.process(s, event)
1810
1811 def resize_event(self):
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\cbook.py in process(self, s, *args, **kwargs)
561 for cid, proxy in list(six.iteritems(self.callbacks[s])):
562 try:
--> 563 proxy(*args, **kwargs)
564 except ReferenceError:
565 self._remove_proxy(proxy)
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\cbook.py in __call__(self, *args, **kwargs)
428 mtd = self.func
429 # invoke the callable and return the result
--> 430 return mtd(*args, **kwargs)
431
432 def __eq__(self, other):
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in _start(self, *args)
659
660 # Now do any initial draw
--> 661 self._init_draw()
662
663 # Add our callback for stepping the animation and
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\animation.py in _init_draw(self)
1222
1223 else:
-> 1224 self._drawn_artists = self._init_func()
1225 if self._blit:
1226 if self._drawn_artists is None:
<ipython-input-1-728862430f94> in init()
10
11 def init():
---> 12 im.set_data([])
13 return im
14
C:\Users\Alexander\Anaconda3\lib\site-packages\matplotlib\image.py in set_data(self, A)
451 if (self._A.ndim not in (2, 3) or
452 (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
--> 453 raise TypeError("Invalid dimensions for image data")
454
455 self._imcache = None
TypeError: Invalid dimensions for image data
Disclaimer: This answer solves the problems in the code itself and allows to run it as python script. It does not solve the problem of animating it in a jupyter notebook. (see comments)
Two things:
You need to set some data to the image in the init function.
The return of init() as well as update() must be a tuple, if you want to use blit=True (otherwise you don't even need a return). Since you only want to blit the image itself, you can use return im, with the comma.
Complete running code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
mat = np.random.random((1000, 50, 50))
print mat[0].shape
def quick_play(dT = 10):
fig, ax = plt.subplots()
im = ax.imshow(mat[0], cmap = "gray")
def init():
im.set_data(mat[0])
return im,
def animate(i):
im.set_data(mat[i])
return im,
ani = animation.FuncAnimation(fig, animate, frames = 100, init_func = init, interval = dT, blit = True)
plt.show()
quick_play()
Related
I have the following code which correctly renders this:
plt.xlabel('Date')
plt.ylabel('Temp')
plt.title('Min and Max temperature 2005-2014')
# Plotting on the first y-axis
minimum=new_df['min']
maximum=new_df['max']
plt.plot(new_df['Date'], new_df['min'], color='orange', label='Min')
plt.plot(new_df['Date'], new_df['max'], color='olive', label='Max')
Now I need to colour the area between the 2 lines:
I tried this:
plt.fill_between(minimum, maximum, color='#539ecd')
but then I get this error:
ValueError Traceback (most recent call last)
/opt/conda/lib/python3.6/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)
/opt/conda/lib/python3.6/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))
/opt/conda/lib/python3.6/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':
/opt/conda/lib/python3.6/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)
/opt/conda/lib/python3.6/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
/opt/conda/lib/python3.6/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()
/opt/conda/lib/python3.6/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
/opt/conda/lib/python3.6/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')
/opt/conda/lib/python3.6/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
/opt/conda/lib/python3.6/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
/opt/conda/lib/python3.6/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')
/opt/conda/lib/python3.6/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
/opt/conda/lib/python3.6/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
/opt/conda/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
1134 renderer.open_group(__name__)
1135
-> 1136 ticks_to_draw = self._update_ticks(renderer)
1137 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1138 renderer)
/opt/conda/lib/python3.6/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
967
968 interval = self.get_view_interval()
--> 969 tick_tups = [t for t in self.iter_ticks()]
970 if self._smart_bounds:
971 # handle inverted limits
/opt/conda/lib/python3.6/site-packages/matplotlib/axis.py in <listcomp>(.0)
967
968 interval = self.get_view_interval()
--> 969 tick_tups = [t for t in self.iter_ticks()]
970 if self._smart_bounds:
971 # handle inverted limits
/opt/conda/lib/python3.6/site-packages/matplotlib/axis.py in iter_ticks(self)
910 Iterate through all of the major and minor ticks.
911 """
--> 912 majorLocs = self.major.locator()
913 majorTicks = self.get_major_ticks(len(majorLocs))
914 self.major.formatter.set_locs(majorLocs)
/opt/conda/lib/python3.6/site-packages/matplotlib/dates.py in __call__(self)
981 def __call__(self):
982 'Return the locations of the ticks'
--> 983 self.refresh()
984 return self._locator()
985
/opt/conda/lib/python3.6/site-packages/matplotlib/dates.py in refresh(self)
1001 def refresh(self):
1002 'Refresh internal information based on current limits.'
-> 1003 dmin, dmax = self.viewlim_to_dt()
1004 self._locator = self.get_locator(dmin, dmax)
1005
/opt/conda/lib/python3.6/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
758 vmin, vmax = vmax, vmin
759
--> 760 return num2date(vmin, self.tz), num2date(vmax, self.tz)
761
762 def _get_unit(self):
/opt/conda/lib/python3.6/site-packages/matplotlib/dates.py in num2date(x, tz)
399 tz = _get_rc_timezone()
400 if not cbook.iterable(x):
--> 401 return _from_ordinalf(x, tz)
402 else:
403 x = np.asarray(x)
/opt/conda/lib/python3.6/site-packages/matplotlib/dates.py in _from_ordinalf(x, tz)
252
253 ix = int(x)
--> 254 dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
255
256 remainder = float(x) - ix
ValueError: ordinal must be >= 1
<matplotlib.figure.Figure at 0x7fb311ea1cf8>
Edit:
dataframe looks like this:
Date min max min2015 max2015
0 2014-01-01 -160 156 -133 11
1 2014-01-02 -267 139 -122 39
2 2014-01-03 -267 133 -67 39
3 2014-01-04 -261 106 -88 44
4 2014-01-05 -150 128 -155 28
and I convert the Date to datetime type like this:
new_df['Date'] = pd.to_datetime(new_df['Date'], infer_datetime_format=True)
Edit:
When I run:
plt.fill_between(new_df['Date'], minimum, maximum)
I get this error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-0f6fcbb48fdc> in <module>()
59
60
---> 61 leaflet_plot_stations(400,'fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89')
<ipython-input-23-0f6fcbb48fdc> in leaflet_plot_stations(binsize, hashid)
44 minimum = new_df['min']
45 maximum = new_df['max']
---> 46 plt.fill_between(new_df['Date'], minimum, maximum)
47 #plt.scatter(new_df['Date'], new_df['min2015'], 'o')
48 #plt.scatter(new_df['Date'], new_df['max2015'], 'o')
/opt/conda/lib/python3.6/site-packages/matplotlib/pyplot.py in fill_between(x, y1, y2, where, interpolate, step, hold, data, **kwargs)
2999 ret = ax.fill_between(x, y1, y2=y2, where=where,
3000 interpolate=interpolate, step=step, data=data,
-> 3001 **kwargs)
3002 finally:
3003 ax._hold = washold
/opt/conda/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
1890 warnings.warn(msg % (label_namer, func.__name__),
1891 RuntimeWarning, stacklevel=2)
-> 1892 return func(ax, *args, **kwargs)
1893 pre_doc = inner.__doc__
1894 if pre_doc is None:
/opt/conda/lib/python3.6/site-packages/matplotlib/axes/_axes.py in fill_between(self, x, y1, y2, where, interpolate, step, **kwargs)
4770
4771 # Convert the arrays so we can work with them
-> 4772 x = ma.masked_invalid(self.convert_xunits(x))
4773 y1 = ma.masked_invalid(self.convert_yunits(y1))
4774 y2 = ma.masked_invalid(self.convert_yunits(y2))
/opt/conda/lib/python3.6/site-packages/numpy/ma/core.py in masked_invalid(a, copy)
2343 cls = type(a)
2344 else:
-> 2345 condition = ~(np.isfinite(a))
2346 cls = MaskedArray
2347 result = a.view(cls)
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Looks like the fill is being tried horizontally over the time axis, and minimum and maximum contain values that aren't dates. I've looked up the documentation:
matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)
That was the first error.
Then with numpy newer than 1.17.0, you could just do:
size = 500
minimum = np.random.normal(0, 100, size)
minimum.sort()
minimum = np.random.randint(250, 300, size) - np.abs(minimum)
df = pd.DataFrame(minimum,
pd.date_range("2005-01-01", periods=size, freq="d"),
columns=['min'],
)
df['max'] = df['min'] + np.random.randint(200, 250, size)
fig = df.plot()
fig.fill_between(df.index, df['min'], df['max'], color='#539ecd')
But from that second traceback, we can see that fill_between is trying ~(np.isfinite(a)) on all the axes. Which isn't supported on older numpy.datetime64, the type of your x-axis.
So we will have to use a numeric x-axis and then change the labels.
df = pd.DataFrame(minimum,
columns=['min'],
)
df['max'] = df['min'] + np.random.randint(200, 250, size)
fig = df.plot()
fig.fill_between(df.index, df['min'], df['max'], color='#539ecd')
# We take the original datetime axis
date_axis = pd.date_range("2005-01-01", periods=size, freq="d")
# and map a function from (axis, tick) -> wanted string
def label(axis, tick):
tick = int(tick)
if tick == len(axis):
tick -= 1
if 0 <= tick < len(axis):
return f"{axis[tick].year}-{axis[tick].month}"
else:
return ' '
fig.set_xticks(fig.get_xticks()) #silence a warning
fig.set_xticklabels(
[label(date_axis, tick) for tick in fig.get_xticks()]
)
fill_between takes the x coordinates as first argument. The following should work:
plt.fill_between(new_df["Date"], minimum, maximum, color="lemonchiffon")
Note that using matplotlib 3.4 I could not reproduce the error. Whether the values in Date were converted to dates or were left as strings, fill_between(minimum, maximum) does not throw an error but does produce unexpected plots.
Edit
Using numpy 1.11.3 and matplotlib 2.0.2, I've been able to reproduce the TypeError raises by np.isfinite (see this post for more information). Indeed this function supports datetime64 only from version 1.17. I highly suggest that you update the versions of matplotlib and numpy. However, using the earlier versions described in this paragraph, the error was bypassed by explicitly casting the dates:
plt.fill_between(np.array(new_df["Date"]), minimum, maximum, color='lemonchiffon')
How can I solve this problem ?
Where I pass the data as a string instead of bytes?
TypeError: a bytes-like object is required, not 'str'
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib import animation
from JSAnimation import IPython_display
def solwave(t, x, c=1):
""" Solitary wave solution of the K deV equation."""
return c/(2*np.cosh(np.sqrt(c)*(x-c*t)/2)*2)
# Initialization
fig = plt.figure()
ax = plt.axes(xlim=(-5, 20), ylim=(0, 0.6))
line, = ax.plot([], [], lw=2)
t=np.linspace(-10,25,91)
x = np.linspace(-5, 20.0, 101)
def init():
line.set_data([], [])
return line,
def animate(i):
y = solwave(t[i], x)
line.set_data(x, y)
return line,
animation.FuncAnimation(fig, animate, init_func=init,
frames=90, interval=30, blit=True)
import numpy as np
# Fix speed
c = 1.0
def solwave(t, x):
""" Solitary wave solution of the K deV equation."""
return c/(2*np.cosh(np.sqrt(c)*(x-c*t)/2)*2)
TypeError Traceback (most recent call last)
D:\Software\Windows\Anaconda\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
343 method = get_real_method(obj, self.print_method)
344 if method is not None:
--> 345 return method()
346 return None
347 else:
D:\Software\Windows\Anaconda\lib\site-packages\JSAnimation\IPython_display.py in anim_to_html(anim, fps,
embed_frames, default_mode)
74 anim.save(f.name, writer=HTMLWriter(fps=fps,
75
embed_frames=embed_frames,
---> 76
default_mode=default_mode))
77 html = open(f.name).read()
78
D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py in
save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata,
extra_anim, savefig_kwargs, progress_callback) 1154 progress_callback(frame_number,
total_frames) 1155 frame_number += 1
-> 1156 writer.grab_frame(**savefig_kwargs) 1157 1158 # Reconnect signal for first draw if necessary
D:\Software\Windows\Anaconda\lib\contextlib.py in __exit__(self, type,
value, traceback)
117 if type is None:
118 try:
--> 119 next(self.gen)
120 except StopIteration:
121 return False
D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py in
saving(self, fig, outfile, dpi, *args, **kwargs)
230 yield self
231 finally:
--> 232 self.finish()
233
234
D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py in
finish(self)
526 # are available to be assembled.
527 self._run()
--> 528 MovieWriter.finish(self) # Will call clean-up
529
530 def cleanup(self):
D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py in
finish(self)
365 def finish(self):
366 '''Finish any processing for writing the movie.'''
--> 367 self.cleanup()
368
369 def grab_frame(self, **savefig_kwargs):
D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py in
cleanup(self)
529
530 def cleanup(self):
--> 531 MovieWriter.cleanup(self)
532
533 # Delete temporary files
D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py in
cleanup(self)
397 self._frame_sink().close()
398 # Use the encoding/errors that universal_newlines would use.
--> 399 out = TextIOWrapper(BytesIO(out)).read()
400 err = TextIOWrapper(BytesIO(err)).read()
401 if out:
TypeError: a bytes-like object is required, not 'str'
<matplotlib.animation.FuncAnimation at 0x1842f83d4e0>
how about editing animation.py as below:
if type(out) is str:
out = TextIOWrapper(BytesIO(out.encode('utf-8'))).read()
err = TextIOWrapper(BytesIO(err.encode('utf-8'))).read()
else:
out = TextIOWrapper(BytesIO(out)).read()
err = TextIOWrapper(BytesIO(err)).read()
you have to edit D:\Software\Windows\Anaconda\lib\site-packages\matplotlib\animation.py
from
399 out = TextIOWrapper(BytesIO(out)).read()
400 err = TextIOWrapper(BytesIO(err)).read()
to
399 out = TextIOWrapper(BytesIO(out.encode('utf-8'))).read()
400 err = TextIOWrapper(BytesIO(err.encode('utf-8'))).read()
I get an error when I plot with colours, and works fine without it. My line colours need to be restricted to 2 defined values.
This works in Jupyter Notebook
import random
xStart = random.sample(range(1, 10), 6)
xStart.sort()
xEnd = [x + random.randint(1, 6) for x in xStart]
yval = list(range(1, 7))
colours = ['r']*6
colours[1] = 'b'
print(xStart)
print(xEnd)
print(yval)
print(colours)
f, ax1 = plt.subplots(figsize=(6,4))
ax1.plot([xStart,xEnd], [yval,yval], '-', linewidth=1) #, color=colours)
plt.show()
This does not work.
If I uncomment the color argument, the code throws an (elaborate) error. While I can draw each line segment in a loop and colour each red or blue, I assume it will be slower than the below code. In this toy example I have 6 lines, but in reality I have 12,000 lines and it takes a few minutes, drawing one line at a time in a loop.
I think the error is related to the size of my colour argument; it is likely expecting 1 (at a time internally) whereas I am providing a list of 6.
import random
xStart = random.sample(range(1, 10), 6)
xStart.sort()
xEnd = [x + random.randint(1, 6) for x in xStart]
yval = list(range(1, 7))
colours = ['r']*6
colours[1] = 'b'
print(xStart)
print(xEnd)
print(yval)
print(colours)
f, ax1 = plt.subplots(figsize=(6,4))
ax1.plot([xStart,xEnd], [yval,yval], '-', linewidth=1, color=colours) #--> Only change from above code
plt.show()
TypeError Traceback (most recent call
last) C:\Anaconda3\lib\site-packages\matplotlib\colors.py in
to_rgba(c, alpha)
131 try:
--> 132 rgba = _colors_full_map.cache[c, alpha]
133 except (KeyError, TypeError): # Not in cache, or unhashable.
TypeError: unhashable type: 'list'
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)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)
C:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in
(fig)
236
237 if 'png' in formats:
--> 238 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
239 if 'retina' in formats or 'png2x' in formats:
240 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)
120
121 bytes_io = BytesIO()
--> 122 fig.canvas.print_figure(bytes_io, **kw)
123 data = bytes_io.getvalue()
124 if fmt == 'svg':
C:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in
print_figure(self, filename, dpi, facecolor, edgecolor, orientation,
format, **kwargs) 2214 orientation=orientation,
2215 dryrun=True,
-> 2216 **kwargs) 2217 renderer = self.figure._cachedRenderer 2218 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)
505
506 def print_png(self, filename_or_obj, *args, **kwargs):
--> 507 FigureCanvasAgg.draw(self)
508 renderer = self.get_renderer()
509 original_dpi = renderer.dpi
C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in
draw(self)
428 # if toolbar:
429 # toolbar.set_cursor(cursors.WAIT)
--> 430 self.figure.draw(self.renderer)
431 finally:
432 # if toolbar:
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in
draw_wrapper(artist, renderer, *args, **kwargs)
53 renderer.start_filter()
54
---> 55 return draw(artist, renderer, *args, **kwargs)
56 finally:
57 if artist.get_agg_filter() is not None:
C:\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self,
renderer) 1297 1298
mimage._draw_list_compositing_images(
-> 1299 renderer, self, artists, self.suppressComposite) 1300 1301
renderer.close_group('figure')
C:\Anaconda3\lib\site-packages\matplotlib\image.py in
_draw_list_compositing_images(renderer, parent, artists, suppress_composite)
136 if not_composite or not has_images:
137 for a in artists:
--> 138 a.draw(renderer)
139 else:
140 # Composite any adjacent images together
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in
draw_wrapper(artist, renderer, *args, **kwargs)
53 renderer.start_filter()
54
---> 55 return draw(artist, renderer, *args, **kwargs)
56 finally:
57 if artist.get_agg_filter() is not None:
C:\Anaconda3\lib\site-packages\matplotlib\axes_base.py in draw(self,
renderer, inframe) 2435 renderer.stop_rasterizing()
2436
-> 2437 mimage._draw_list_compositing_images(renderer, self, artists) 2438 2439 renderer.close_group('axes')
C:\Anaconda3\lib\site-packages\matplotlib\image.py in
_draw_list_compositing_images(renderer, parent, artists, suppress_composite)
136 if not_composite or not has_images:
137 for a in artists:
--> 138 a.draw(renderer)
139 else:
140 # Composite any adjacent images together
C:\Anaconda3\lib\site-packages\matplotlib\artist.py in
draw_wrapper(artist, renderer, *args, **kwargs)
53 renderer.start_filter()
54
---> 55 return draw(artist, renderer, *args, **kwargs)
56 finally:
57 if artist.get_agg_filter() is not None:
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in draw(self,
renderer)
765 self._set_gc_clip(gc)
766
--> 767 ln_color_rgba = self._get_rgba_ln_color()
768 gc.set_foreground(ln_color_rgba, isRGBA=True)
769 gc.set_alpha(ln_color_rgba[3])
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in
_get_rgba_ln_color(self, alt) 1267 1268 def _get_rgba_ln_color(self, alt=False):
-> 1269 return mcolors.to_rgba(self._color, self._alpha) 1270 1271 # some aliases....
C:\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c,
alpha)
132 rgba = _colors_full_map.cache[c, alpha]
133 except (KeyError, TypeError): # Not in cache, or unhashable.
--> 134 rgba = _to_rgba_no_colorcycle(c, alpha)
135 try:
136 _colors_full_map.cache[c, alpha] = rgba
C:\Anaconda3\lib\site-packages\matplotlib\colors.py in
_to_rgba_no_colorcycle(c, alpha)
183 # float)andnp.array(...).astype(float)` all convert "0.5" to 0.5.
184 # Test dimensionality to reject single floats.
--> 185 raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
186 # Return a tuple to prevent the cached value from being modified.
187 c = tuple(c.astype(float))
ValueError: Invalid RGBA argument: ['r', 'b', 'r', 'r', 'r', 'r']
OK thanks to Bazingaa and this thread, How to get different colored lines for different plots in a single figure?
...the final code is as follows.
Since I am drawing multiple lines with one ax.plot() command, the colour argument will not take. IMHO it should since it logically makes sense and should be an enhancement matplotlib does. Nonetheless, here is the solution as Bazingaa pointed out to me.
For those interested, as expected this code does run a LOT faster compared with drawing 12K lines in a loop (in order to draw & color them one at a time with individual ax.plot() commands).
import random
xStart = random.sample(range(1, 10), 6)
xStart.sort()
xEnd = [x + random.randint(1, 6) for x in xStart]
yval = list(range(1, 7))
colours = ['r']*6
colours[1] = 'b'
f, ax1 = plt.subplots(figsize=(6,4))
ax1.plot([xStart,xEnd], [yval,yval], '-', linewidth=1) #, color=colours) #Leaving the color argument commented
#Add new code to colour after the fact
for idx,line in enumerate(ax1.lines):
line.set_color(colours[idx])
plt.show()
%pylab
x = linspace(-10., 10., 1000)
plot(x, sin(x))
PyAssertionError Traceback (most recent call last)
<ipython-input-41-c9b44dd20001> in <module>()
----> 1 plot(x, sin(x))
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.pyc in plot(*args, **kwargs)
3305 #_autogen_docstring(Axes.plot)
3306 def plot(*args, **kwargs):
-> 3307 ax = gca()
3308 # Deprecated: allow callers to override the hold state
3309 # by passing hold=True|False
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.pyc in gca(**kwargs)
948 matplotlib.figure.Figure.gca : The figure's gca method.
949 """
--> 950 return gcf().gca(**kwargs)
951
952 # More ways of creating axes:
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.pyc in gcf()
584 return figManager.canvas.figure
585 else:
--> 586 return figure()
587
588
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.pyc in figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, **kwargs)
533 frameon=frameon,
534 FigureClass=FigureClass,
--> 535 **kwargs)
536
537 if figLabel:
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wxagg.pyc in new_figure_manager(num, *args, **kwargs)
114 fig = FigureClass(*args, **kwargs)
115
--> 116 return new_figure_manager_given_figure(num, fig)
117
118
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wxagg.pyc in new_figure_manager_given_figure(num, figure)
121 Create a new figure manager instance for the given figure.
122 """
--> 123 frame = FigureFrameWxAgg(num, figure)
124 figmgr = frame.get_figure_manager()
125 if matplotlib.is_interactive():
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wx.pyc in __init__(self, num, fig)
1262 # of the frame - so appearance is closer to GTK version
1263
-> 1264 self.toolbar = self._get_toolbar(statbar)
1265
1266 if self.toolbar is not None:
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wxagg.pyc in _get_toolbar(self, statbar)
26 def _get_toolbar(self, statbar):
27 if matplotlib.rcParams['toolbar'] == 'toolbar2':
---> 28 toolbar = NavigationToolbar2WxAgg(self.canvas)
29 toolbar.set_status_bar(statbar)
30 else:
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wx.pyc in __init__(self, canvas)
1569 def __init__(self, canvas):
1570 wx.ToolBar.__init__(self, canvas.GetParent(), -1)
-> 1571 NavigationToolbar2.__init__(self, canvas)
1572 self.canvas = canvas
1573 self._idle = True
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backend_bases.pyc in __init__(self, canvas)
2750 self._active = None
2751 self._lastCursor = None
-> 2752 self._init_toolbar()
2753 self._idDrag = self.canvas.mpl_connect(
2754 'motion_notify_event', self.mouse_move)
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wx.pyc in _init_toolbar(self)
1595 self.wx_ids[text] = wx.NewId()
1596 wxc._AddTool(self, self.wx_ids, text,
-> 1597 _load_bitmap(image_file + '.png'),
1598 tooltip_text)
1599
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wx.pyc in _load_bitmap(filename)
1423 raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename)
1424
-> 1425 bmp = wx.Bitmap(bmpFilename)
1426 return bmp
1427
C:\Users\RD\AppData\Local\Enthought\Canopy\User\lib\site-packages\wx\_gdi.pyc in __init__(self, *args, **kwargs)
646 Loads a bitmap from a file.
647 """
--> 648 _gdi_.Bitmap_swiginit(self,_gdi_.new_Bitmap(*args, **kwargs))
649 __swig_destroy__ = _gdi_.delete_Bitmap
650 __del__ = lambda self : None;
PyAssertionError: C++ assertion "strcmp(setlocale(LC_ALL, NULL), "C") == 0" failed at ..\..\src\common\intl.cpp(1449) in wxLocale::GetInfo(): You probably called setlocale() directly instead of using wxLocale and now there is a mismatch between C/C++ and Windows locale.
Things are going to break, please only change locale by creating wxLocale objects to avoid this!
I am trying to plot the results.How can I plot the results? I am getting the PyAssertion error. How can I solve the error?
I have two numpy arrays 1D, one is time of measurement in datetime64 format, for example:
array([2011-11-15 01:08:11, 2011-11-16 02:08:04, ..., 2012-07-07 11:08:00], dtype=datetime64[us])
and other array of same length and dimension with integer data.
I'd like to make a plot in matplotlib time vs data. If I put the data directly, this is what I get:
plot(timeSeries, data)
Is there a way to get time in more natural units? For example in this case months/year would be fine.
EDIT:
I have tried Gustav Larsson's suggestion however I get an error:
Out[128]:
[<matplotlib.lines.Line2D at 0x419aad0>]
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
/usr/lib/python2.7/dist-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 = []
/usr/lib/python2.7/dist-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:
/usr/lib/python2.7/dist-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:
/usr/lib/pymodules/python2.7/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
1981 orientation=orientation,
1982 dryrun=True,
-> 1983 **kwargs)
1984 renderer = self.figure._cachedRenderer
1985 bbox_inches = self.figure.get_tightbbox(renderer)
/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
467
468 def print_png(self, filename_or_obj, *args, **kwargs):
--> 469 FigureCanvasAgg.draw(self)
470 renderer = self.get_renderer()
471 original_dpi = renderer.dpi
/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.pyc in draw(self)
419
420 try:
--> 421 self.figure.draw(self.renderer)
422 finally:
423 RendererAgg.lock.release()
/usr/lib/pymodules/python2.7/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
53 def draw_wrapper(artist, renderer, *args, **kwargs):
54 before(artist, renderer)
---> 55 draw(artist, renderer, *args, **kwargs)
56 after(artist, renderer)
57
/usr/lib/pymodules/python2.7/matplotlib/figure.pyc in draw(self, renderer)
896 dsu.sort(key=itemgetter(0))
897 for zorder, a, func, args in dsu:
--> 898 func(*args)
899
900 renderer.close_group('figure')
/usr/lib/pymodules/python2.7/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
53 def draw_wrapper(artist, renderer, *args, **kwargs):
54 before(artist, renderer)
---> 55 draw(artist, renderer, *args, **kwargs)
56 after(artist, renderer)
57
/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in draw(self, renderer, inframe)
1995
1996 for zorder, a in dsu:
-> 1997 a.draw(renderer)
1998
1999 renderer.close_group('axes')
/usr/lib/pymodules/python2.7/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
53 def draw_wrapper(artist, renderer, *args, **kwargs):
54 before(artist, renderer)
---> 55 draw(artist, renderer, *args, **kwargs)
56 after(artist, renderer)
57
/usr/lib/pymodules/python2.7/matplotlib/axis.pyc in draw(self, renderer, *args, **kwargs)
1039 renderer.open_group(__name__)
1040
-> 1041 ticks_to_draw = self._update_ticks(renderer)
1042 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
1043
/usr/lib/pymodules/python2.7/matplotlib/axis.pyc in _update_ticks(self, renderer)
929
930 interval = self.get_view_interval()
--> 931 tick_tups = [ t for t in self.iter_ticks()]
932 if self._smart_bounds:
933 # handle inverted limits
/usr/lib/pymodules/python2.7/matplotlib/axis.pyc in iter_ticks(self)
876 Iterate through all of the major and minor ticks.
877 """
--> 878 majorLocs = self.major.locator()
879 majorTicks = self.get_major_ticks(len(majorLocs))
880 self.major.formatter.set_locs(majorLocs)
/usr/lib/pymodules/python2.7/matplotlib/dates.pyc in __call__(self)
747 def __call__(self):
748 'Return the locations of the ticks'
--> 749 self.refresh()
750 return self._locator()
751
/usr/lib/pymodules/python2.7/matplotlib/dates.pyc in refresh(self)
756 def refresh(self):
757 'Refresh internal information based on current limits.'
--> 758 dmin, dmax = self.viewlim_to_dt()
759 self._locator = self.get_locator(dmin, dmax)
760
/usr/lib/pymodules/python2.7/matplotlib/dates.pyc in viewlim_to_dt(self)
528 def viewlim_to_dt(self):
529 vmin, vmax = self.axis.get_view_interval()
--> 530 return num2date(vmin, self.tz), num2date(vmax, self.tz)
531
532 def _get_unit(self):
/usr/lib/pymodules/python2.7/matplotlib/dates.pyc in num2date(x, tz)
287 """
288 if tz is None: tz = _get_rc_timezone()
--> 289 if not cbook.iterable(x): return _from_ordinalf(x, tz)
290 else: return [_from_ordinalf(val, tz) for val in x]
291
/usr/lib/pymodules/python2.7/matplotlib/dates.pyc in _from_ordinalf(x, tz)
201 if tz is None: tz = _get_rc_timezone()
202 ix = int(x)
--> 203 dt = datetime.datetime.fromordinal(ix)
204 remainder = float(x) - ix
205 hour, remainder = divmod(24*remainder, 1)
OverflowError: signed integer is greater than maximum
Could this be an bug? Or am I missing something. I also tried something simple:
import matplotlib.pyplot as plt
import numpy as np
dates=np.array(["2011-11-13", "2011-11-14", "2011-11-15", "2011-11-16", "2011-11-19"], dtype='datetime64[us]')
data=np.array([1, 2, 3, 4, 5])
plt.plot_date(dates, data)
plt.show()
I still get this error:
OverflowError: signed integer is greater than maximum
I don't understand what am I doing wrong. ipython 0.13, matplotlib 1.1, Ubuntu 12.04 x64.
FINAL EDIT:
It seems that matplotlib doesn't support dtype=datetime64, so I needed to convert the timeSeries to ordinary datetime.datetime from datetime.
from datetime import datetime
a=np.datetime64('2002-06-28').astype(datetime)
plot_date(a,2)
Matplotlib>=2.2 natively supports plotting datetime64 arrays. See https://github.com/matplotlib/matplotlib/blob/master/doc/users/prev_whats_new/whats_new_2.2.rst#support-for-numpydatetime64:
Matplotlib has supported datetime.datetime dates for a long time in
matplotlib.dates. We now support numpy.datetime64 dates as well.
Anywhere that dateime.datetime could be used, numpy.datetime64 can be
used. eg:
time = np.arange('2005-02-01', '2005-02-02', dtype='datetime64[h]')
plt.plot(time)
You might want to try this:
plot_date(timeSeries, data)
By default, the x axis will be considered a date axis, and y a regular one. This can be customized.
I had a similar porblem. Sometimes, the date axis plotted corectly my np.datetim64 array and at other times it did not with the same time array, giving some non-recognizible integer values on the date axis instead.
The reason turned out to my having set ax.xscale('linear') after first having worked with a logarithmmic scale. Removing the ax.xscale('linear') solved the problem. A linear axis is not a datetime axis, I learned.