I'm trying to plot and save an interactive figure using matplotlib in Jupyter notebook using the following code:
%matplotlib notebook
plt.figure()
plt.imshow([[1, 2, 3],[4, 5, 6]])
plt.savefig('delete.png')
When I do this, I get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backend_bases.py in _wait_cursor_for_draw_cm(self)
2772 try:
-> 2773 self.set_cursor(cursors.WAIT)
2774 yield
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backends/backend_webagg_core.py in set_cursor(self, cursor)
380 if cursor != self.cursor:
--> 381 self.canvas.send_event("cursor", cursor=cursor)
382 self.cursor = cursor
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backends/backend_webagg_core.py in send_event(self, event_type, **kwargs)
345 def send_event(self, event_type, **kwargs):
--> 346 self.manager._send_event(event_type, **kwargs)
347
AttributeError: 'NoneType' object has no attribute '_send_event'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last) <ipython-input-8-de5d3bbf172d> in <module>
2 plt.figure()
3 plt.imshow([[1, 2, 3],[4, 5, 6]])
----> 4 plt.savefig('delete.png')
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/pyplot.py in savefig(*args, **kwargs)
721 def savefig(*args, **kwargs):
722 fig = gcf()
--> 723 res = fig.savefig(*args, **kwargs)
724 fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
725 return res
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/figure.py in savefig(self, fname, transparent, **kwargs)
2201 self.patch.set_visible(frameon)
2202
-> 2203 self.canvas.print_figure(fname, **kwargs)
2204
2205 if frameon:
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backend_bases.py in
print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
2091 orientation=orientation,
2092 bbox_inches_restore=_bbox_inches_restore,
-> 2093 **kwargs)
2094 finally:
2095 if bbox_inches and restore_bbox:
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, metadata, pil_kwargs, *args,
**kwargs)
512 }
513
--> 514 FigureCanvasAgg.draw(self)
515 if pil_kwargs is not None:
516 from PIL import Image
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
390 with RendererAgg.lock, \
391 (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
--> 392 else nullcontext()):
393 self.figure.draw(self.renderer)
394 # A GUI class may be need to update a window using this draw, so
~/anaconda3/envs/asd/lib/python3.6/contextlib.py in __enter__(self)
79 def __enter__(self):
80 try:
---> 81 return next(self.gen)
82 except StopIteration:
83 raise RuntimeError("generator didn't yield") from None
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backend_bases.py in _wait_cursor_for_draw_cm(self)
2774 yield
2775 finally:
-> 2776 self.set_cursor(self._lastCursor)
2777 else:
2778 yield
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backends/backend_webagg_core.py in set_cursor(self, cursor)
379 def set_cursor(self, cursor):
380 if cursor != self.cursor:
--> 381 self.canvas.send_event("cursor", cursor=cursor)
382 self.cursor = cursor
383
~/anaconda3/envs/asd/lib/python3.6/site-packages/matplotlib/backends/backend_webagg_core.py in send_event(self, event_type, **kwargs)
344
345 def send_event(self, event_type, **kwargs):
--> 346 self.manager._send_event(event_type, **kwargs)
347
348
AttributeError: 'NoneType' object has no attribute '_send_event'
The figure itself renders fine when I get rid of the savefig command. Furthermore, both rendering and saving work fine when I use %matplotlib inline instead of %matplotlib notebook. What is causing this issue and how can I save figures when using %matplotlib notebook?
Related
I am trying to get a the result of a Google Bigquery query in a pandas dataframe (in Jupiter notebook).
But everytime I try to run the query I get a DeadlineExceeded: 504 Deadline Exceeded.
This happens not only for queries in my own BQ project but also for other projects.
I have tried a lot of option to run the query like in here: https://cloud.google.com/bigquery/docs/bigquery-storage-python-pandas
Anyone have a idea how to fix this?
Query:
%load_ext google.cloud.bigquery
%%bigquery tax_forms --use_bqstorage_api
SELECT * FROM `bigquery-public-data.irs_990.irs_990_2012`
---------------------------------------------------------------------------
_MultiThreadedRendezvous Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\grpc_helpers.py in error_remapped_callable(*args, **kwargs)
149 prefetch_first = getattr(callable_, "_prefetch_first_result_", True)
--> 150 return _StreamingResponseIterator(result, prefetch_first_result=prefetch_first)
151 except grpc.RpcError as exc:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\grpc_helpers.py in __init__(self, wrapped, prefetch_first_result)
72 if prefetch_first_result:
---> 73 self._stored_first_result = six.next(self._wrapped)
74 except TypeError:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\grpc\_channel.py in __next__(self)
415 def __next__(self):
--> 416 return self._next()
417
~\AppData\Local\Continuum\anaconda3\lib\site-packages\grpc\_channel.py in _next(self)
705 elif self._state.code is not None:
--> 706 raise self
707
_MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with:
status = StatusCode.DEADLINE_EXCEEDED
details = "Deadline Exceeded"
debug_error_string = "{"created":"#1597838569.388000000","description":"Error received from peer ipv4:172.217.168.202:443","file":"src/core/lib/surface/call.cc","file_line":1062,"grpc_message":"Deadline Exceeded","grpc_status":4}"
>
The above exception was the direct cause of the following exception:
DeadlineExceeded Traceback (most recent call last)
<ipython-input-2-4fdaec7219df> in <module>
----> 1 get_ipython().run_cell_magic('bigquery', 'tax_forms --use_bqstorage_api', 'SELECT * FROM `bigquery-public-data.irs_990.irs_990_2012`\n')
~\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2357 with self.builtin_trap:
2358 args = (magic_arg_s, cell)
-> 2359 result = fn(*args, **kwargs)
2360 return result
2361
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\magics.py in _cell_magic(line, query)
589 )
590 else:
--> 591 result = query_job.to_dataframe(bqstorage_client=bqstorage_client)
592
593 if args.destination_var:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\job.py in to_dataframe(self, bqstorage_client, dtypes, progress_bar_type, create_bqstorage_client, date_as_object)
3381 progress_bar_type=progress_bar_type,
3382 create_bqstorage_client=create_bqstorage_client,
-> 3383 date_as_object=date_as_object,
3384 )
3385
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\table.py in to_dataframe(self, bqstorage_client, dtypes, progress_bar_type, create_bqstorage_client, date_as_object)
1726 progress_bar_type=progress_bar_type,
1727 bqstorage_client=bqstorage_client,
-> 1728 create_bqstorage_client=create_bqstorage_client,
1729 )
1730
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\table.py in to_arrow(self, progress_bar_type, bqstorage_client, create_bqstorage_client)
1544 record_batches = []
1545 for record_batch in self._to_arrow_iterable(
-> 1546 bqstorage_client=bqstorage_client
1547 ):
1548 record_batches.append(record_batch)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\table.py in _to_page_iterable(self, bqstorage_download, tabledata_list_download, bqstorage_client)
1433 ):
1434 if bqstorage_client is not None:
-> 1435 for item in bqstorage_download():
1436 yield item
1437 return
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\_pandas_helpers.py in _download_table_bqstorage(project_id, table, bqstorage_client, preserve_order, selected_fields, page_to_item)
723 # Call result() on any finished threads to raise any
724 # exceptions encountered.
--> 725 future.result()
726
727 try:
~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
426 raise CancelledError()
427 elif self._state == FINISHED:
--> 428 return self.__get_result()
429
430 self._condition.wait(timeout)
~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
382 def __get_result(self):
383 if self._exception:
--> 384 raise self._exception
385 else:
386 return self._result
~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\thread.py in run(self)
55
56 try:
---> 57 result = self.fn(*self.args, **self.kwargs)
58 except BaseException as exc:
59 self.future.set_exception(exc)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery\_pandas_helpers.py in _download_table_bqstorage_stream(download_state, bqstorage_client, session, stream, worker_queue, page_to_item)
591 rowstream = bqstorage_client.read_rows(position).rows(session)
592 else:
--> 593 rowstream = bqstorage_client.read_rows(stream.name).rows(session)
594
595 for page in rowstream.pages:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery_storage_v1\client.py in read_rows(self, name, offset, retry, timeout, metadata)
120 retry=retry,
121 timeout=timeout,
--> 122 metadata=metadata,
123 )
124 return reader.ReadRowsStream(
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\cloud\bigquery_storage_v1\gapic\big_query_read_client.py in read_rows(self, read_stream, offset, retry, timeout, metadata)
370
371 return self._inner_api_calls["read_rows"](
--> 372 request, retry=retry, timeout=timeout, metadata=metadata
373 )
374
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\gapic_v1\method.py in __call__(self, *args, **kwargs)
143 kwargs["metadata"] = metadata
144
--> 145 return wrapped_func(*args, **kwargs)
146
147
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\retry.py in retry_wrapped_func(*args, **kwargs)
284 sleep_generator,
285 self._deadline,
--> 286 on_error=on_error,
287 )
288
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\retry.py in retry_target(target, predicate, sleep_generator, deadline, on_error)
182 for sleep in sleep_generator:
183 try:
--> 184 return target()
185
186 # pylint: disable=broad-except
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\timeout.py in func_with_timeout(*args, **kwargs)
212 """Wrapped function that adds timeout."""
213 kwargs["timeout"] = next(timeouts)
--> 214 return func(*args, **kwargs)
215
216 return func_with_timeout
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\api_core\grpc_helpers.py in error_remapped_callable(*args, **kwargs)
150 return _StreamingResponseIterator(result, prefetch_first_result=prefetch_first)
151 except grpc.RpcError as exc:
--> 152 six.raise_from(exceptions.from_grpc_error(exc), exc)
153
154 return error_remapped_callable
~\AppData\Local\Continuum\anaconda3\lib\site-packages\six.py in raise_from(value, from_value)
DeadlineExceeded: 504 Deadline Exceeded
Let me know if you need to know more. Thanks in advance.
Rutger
It turned out to be a conflict between a Conda package and a pip packages.
I resolved it by reinstall all the packages.
I ran the same program on two different data sources (a CSV file & MYSQL database), CSV import runs fine but MYSQL import throws the numpy type error:
I'm guessing issue may lie with these 2 points:
1. Data import issues - INT, TEXT etc? I'm using VARCHAR for the data.
2. Issue with how matplotlib works with Panda dataframes?
I'm new so please treat me as one :)
import pandas as pd
import numpy as np
import matplotlib.pyplot as pp
import seaborn
from sqlalchemy import create_engine
import pymysql
engine = create_engine("mysql+pymysql://root:root#127.0.0.1:3306/babynames",echo=False)
names = pd.read_sql_query('select * from BABYNAMES',engine)
names_indexed = names.set_index(['gender','name','year']).sort_index()
def plotname(gender, name):
data = names_indexed.loc[gender, name]
pp.plot(data.index, data.values)
plotname('F','Nancy')
Error code:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-9d981bcf8365> in <module>()
----> 1 plotname('F','Nancy')
<ipython-input-31-85c728659ad0> in plotname(gender, name)
1 def plotname(gender, name):
2 data = allyears_indexed.loc[gender, name]
----> 3 pp.plot(data.index, data.values)
~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in plot(*args, **kwargs)
3361 mplDeprecation)
3362 try:
-> 3363 ret = ax.plot(*args, **kwargs)
3364 finally:
3365 ax._hold = washold
~/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
1865 "the Matplotlib list!)" % (label_namer, func.__name__),
1866 RuntimeWarning, stacklevel=2)
-> 1867 return func(ax, *args, **kwargs)
1868
1869 inner.__doc__ = _add_data_doc(inner.__doc__,
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs)
1526 kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
1527
-> 1528 for line in self._get_lines(*args, **kwargs):
1529 self.add_line(line)
1530 lines.append(line)
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs)
404 this += args[0],
405 args = args[1:]
--> 406 for seg in self._plot_args(this, kwargs):
407 yield seg
408
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
381 x, y = index_of(tup[-1])
382
--> 383 x, y = self._xy_from_xy(x, y)
384
385 if self.command == 'plot':
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
214 if self.axes.xaxis is not None and self.axes.yaxis is not None:
215 bx = self.axes.xaxis.update_units(x)
--> 216 by = self.axes.yaxis.update_units(y)
217
218 if self.command != 'plot':
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in update_units(self, data)
1467 neednew = self.converter != converter
1468 self.converter = converter
-> 1469 default = self.converter.default_units(data, self)
1470 if default is not None and self.units is None:
1471 self.set_units(default)
~/anaconda3/lib/python3.7/site-packages/matplotlib/category.py in default_units(data, axis)
113 # default_units->axis_info->convert
114 if axis.units is None:
--> 115 axis.set_units(UnitData(data))
116 else:
117 axis.units.update(data)
~/anaconda3/lib/python3.7/site-packages/matplotlib/category.py in __init__(self, data)
180 self._counter = itertools.count(start=0)
181 if data is not None:
--> 182 self.update(data)
183
184 def update(self, data):
~/anaconda3/lib/python3.7/site-packages/matplotlib/category.py in update(self, data)
197 data = np.atleast_1d(np.array(data, dtype=object))
198
--> 199 for val in OrderedDict.fromkeys(data):
200 if not isinstance(val, VALID_TYPES):
201 raise TypeError("{val!r} is not a string".format(val=val))
TypeError: unhashable type: 'numpy.ndarray'
I was right, the issue was with the data types. I created a new table replacing VARCHAR for INT and then used the same code from above and the program worked perfectly.
After building a custom style and saving it in a ".mplstyle" folder, I then import this mplstyle into a new script. Unfortunately I get some errors.
home/local/lib/python2.7/site-packages/matplotlib/__init__.py:1102: UserWarning: Bad val "[3.7, 1.6]" on line #183
"lines.dashed_pattern : [3.7, 1.6]
"
in file "/home/plotting_tools/codepan.mplstyle"
Key lines.dashed_pattern: Could not convert all entries to floats
(val, error_details, msg))
/home/local/lib/python2.7/site-packages/matplotlib/__init__.py:1102: UserWarning: Bad val "[1.0, 1.65]" on line #184
"lines.dotted_pattern : [1.0, 1.65]
"
in file "/home/plotting_tools/codepan.mplstyle"
Key lines.dotted_pattern: Could not convert all entries to floats
(val, error_details, msg))
AttributeErrorTraceback (most recent call last)
/home/local/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
332 pass
333 else:
--> 334 return printer(obj)
335 # Finally look for special method names
336 method = get_real_method(obj, self.print_method)
/home/local/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in <lambda>(fig)
239
240 if 'png' in formats:
--> 241 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
242 if 'retina' in formats or 'png2x' in formats:
243 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
/home/local/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt, bbox_inches, **kwargs)
123
124 bytes_io = BytesIO()
--> 125 fig.canvas.print_figure(bytes_io, **kw)
126 data = bytes_io.getvalue()
127 if fmt == 'svg':
/home/local/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
2210 orientation=orientation,
2211 dryrun=True,
-> 2212 **kwargs)
2213 renderer = self.figure._cachedRenderer
2214 bbox_inches = self.figure.get_tightbbox(renderer)
/home/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
511
512 def print_png(self, filename_or_obj, *args, **kwargs):
--> 513 FigureCanvasAgg.draw(self)
514 renderer = self.get_renderer()
515 original_dpi = renderer.dpi
/home/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
431 # if toolbar:
432 # toolbar.set_cursor(cursors.WAIT)
--> 433 self.figure.draw(self.renderer)
434 # A GUI class may be need to update a window using this draw, so
435 # don't forget to call the superclass.
/home/local/lib/python2.7/site-packages/matplotlib/artist.pyc 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:
/home/local/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
1470
1471 if self.frameon:
-> 1472 self.patch.draw(renderer)
1473
1474 mimage._draw_list_compositing_images(
/home/local/lib/python2.7/site-packages/matplotlib/artist.pyc 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:
/home/local/lib/python2.7/site-packages/matplotlib/patches.pyc in draw(self, renderer)
556 renderer = PathEffectRenderer(self.get_path_effects(), renderer)
557
--> 558 renderer.draw_path(gc, tpath, affine, rgbFace)
559
560 gc.restore()
/home/local/lib/python2.7/site-packages/matplotlib/patheffects.pyc in draw_path(self, gc, tpath, affine, rgbFace)
107 def draw_path(self, gc, tpath, affine, rgbFace=None):
108 for path_effect in self._path_effects:
--> 109 path_effect.draw_path(self._renderer, gc, tpath, affine,
110 rgbFace)
111
AttributeError: 'unicode' object has no attribute 'draw_path'<Figure size 432x288 with 1 Axes>
I suspect it is something to do with how I format the ".mplstyle" file, but I'm not too sure. Let me know if you need further information about my computer or the script I'm running.
EDIT
Here's the code I use
# Example of Use
import matplotlib.pyplot as plt
#plt.style.use("codepan.mplstyle")
plt.style.use('ggplot')
n = 50
raw_data = np.random.randn(n)*10
plt.plot(raw_data)
plt.show()
Here's a snippet from the mplstyle file
lines.dashdot_pattern : [6.4, 1.6, 1.0, 1.6]
lines.dashed_pattern : [3.7, 1.6]
lines.dotted_pattern : [1.0, 1.65]
You want to remove the square brackets from those lines
i.e. they should look like:
lines.dashdot_pattern : 6.4, 1.6, 1.0, 1.6
lines.dashed_pattern : 3.7, 1.6
lines.dotted_pattern : 1.0, 1.65
See, for example, here in the classic.mplstyle example sheet.
I want to plot a line plot from a dataframe, one line for each column (the number of columns vary). e.g.
In:
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame (index = range (1,6),columns=['a','b'])
df['a'] = [1,1,1,1,1]
df['b']=[5,5,5,5,5]
df
Out:
a b
1 1 5
2 1 5
3 1 5
4 1 5
5 1 5
I am using subplots because I want to add other plots to the same axes, with the same colours. I am sending .plot a list of colours:
fig,ax=plt.subplots()
colours = ['r', 'b','g','y','m','c'][0:len(df.columns)]
ax.plot(df,linestyle = '-',color=colours)
plt.show()
I get a ValueError: Invalid RGBA argument: ['r','b'] exception. Full error message is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
154 try:
--> 155 rgba = _colors_full_map.cache[c, alpha]
156 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:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
226
227 if 'png' in formats:
--> 228 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
229 if 'retina' in formats or 'png2x' in formats:
230 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
2208 orientation=orientation,
2209 dryrun=True,
-> 2210 **kwargs)
2211 renderer = self.figure._cachedRenderer
2212 bbox_inches = self.figure.get_tightbbox(renderer)
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
509
510 def print_png(self, filename_or_obj, *args, **kwargs):
--> 511 FigureCanvasAgg.draw(self)
512 renderer = self.get_renderer()
513 original_dpi = renderer.dpi
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
429 # if toolbar:
430 # toolbar.set_cursor(cursors.WAIT)
--> 431 self.figure.draw(self.renderer)
432 # A GUI class may be need to update a window using this draw, so
433 # don't forget to call the superclass.
C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
1473
1474 mimage._draw_list_compositing_images(
-> 1475 renderer, self, artists, self.suppressComposite)
1476
1477 renderer.close_group('figure')
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
139 if not_composite or not has_images:
140 for a in artists:
--> 141 a.draw(renderer)
142 else:
143 # Composite any adjacent images together
C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
2605 renderer.stop_rasterizing()
2606
-> 2607 mimage._draw_list_compositing_images(renderer, self, artists)
2608
2609 renderer.close_group('axes')
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
139 if not_composite or not has_images:
140 for a in artists:
--> 141 a.draw(renderer)
142 else:
143 # Composite any adjacent images together
C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\lines.py in draw(self, renderer)
759 self._set_gc_clip(gc)
760
--> 761 ln_color_rgba = self._get_rgba_ln_color()
762 gc.set_foreground(ln_color_rgba, isRGBA=True)
763 gc.set_alpha(ln_color_rgba[3])
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\lines.py in _get_rgba_ln_color(self, alt)
1260
1261 def _get_rgba_ln_color(self, alt=False):
-> 1262 return mcolors.to_rgba(self._color, self._alpha)
1263
1264 # some aliases....
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
155 rgba = _colors_full_map.cache[c, alpha]
156 except (KeyError, TypeError): # Not in cache, or unhashable.
--> 157 rgba = _to_rgba_no_colorcycle(c, alpha)
158 try:
159 _colors_full_map.cache[c, alpha] = rgba
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
206 # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
207 # Test dimensionality to reject single floats.
--> 208 raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
209 # Return a tuple to prevent the cached value from being modified.
210 c = tuple(c.astype(float))
ValueError: Invalid RGBA argument: ['r', 'b']
<Figure size 432x288 with 1 Axes>
What am I doing wrong? How should I pass a list of colours, one for each column?
matplotlib's plot function doesn't accept a list of colors like that. However, if you use the method DataFrame.plot, you can specify colors that way.
df.plot(linestyle='-', color=colours, ax=ax)
%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?