This seems pretty simple, but for some reason, I can't get it to work. This is in pandas 1.2.3 and matplotlib 3.4.0 running on an anaconda's python 3.8.8 on Windows 10 64-bit, inside a Jupyter notebook locally.
I've created a replication below. First, a working version; note the commented out label line:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df_test = pd.DataFrame(np.random.randn(1000, 4), columns=list("ABCD"))
df_test.plot(kind="scatter", x="A", y="B",
alpha=0.4,
figsize=(10,7),
#label="la la",
s=df_test["C"]*100,
c="D",
cmap=plt.get_cmap("jet"),
colorbar=True,
)
plt.legend()
Running the above gives a complaint No handles with labels found to put in legend (as expected) and some deprecation warnings, but shows a chart. The dots are nicely colored, and you might even see the empty legend box.
Now, uncomment the label line:
df_test.plot(kind="scatter", x="A", y="B",
alpha=0.4,
figsize=(10,7),
label="la la",
s=df_test["C"]*100,
c="D",
cmap=plt.get_cmap("jet"),
colorbar=True,
)
plt.legend()
and when I run this, I get a TypeError: object of type 'NoneType' has no len() error like the below:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
D:\anaconda\envs\tf-gpu\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)
D:\anaconda\envs\tf-gpu\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
246
247 if 'png' in formats:
--> 248 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
249 if 'retina' in formats or 'png2x' in formats:
250 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
D:\anaconda\envs\tf-gpu\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
130 FigureCanvasBase(fig)
131
--> 132 fig.canvas.print_figure(bytes_io, **kw)
133 data = bytes_io.getvalue()
134 if fmt == 'svg':
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2228 else suppress())
2229 with ctx:
-> 2230 self.figure.draw(renderer)
2231
2232 if bbox_inches:
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
72 #wraps(draw)
73 def draw_wrapper(artist, renderer, *args, **kwargs):
---> 74 result = draw(artist, renderer, *args, **kwargs)
75 if renderer._rasterizing:
76 renderer.stop_rasterizing()
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49 renderer.start_filter()
50
---> 51 return draw(artist, renderer, *args, **kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
2732
2733 self.patch.draw(renderer)
-> 2734 mimage._draw_list_compositing_images(
2735 renderer, self, artists, self.suppressComposite)
2736
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130 if not_composite or not has_images:
131 for a in artists:
--> 132 a.draw(renderer)
133 else:
134 # Composite any adjacent images together
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49 renderer.start_filter()
50
---> 51 return draw(artist, renderer, *args, **kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*inner_args, **inner_kwargs)
429 else deprecation_addendum,
430 **kwargs)
--> 431 return func(*inner_args, **inner_kwargs)
432
433 return wrapper
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
2923 renderer.stop_rasterizing()
2924
-> 2925 mimage._draw_list_compositing_images(renderer, self, artists)
2926
2927 renderer.close_group('axes')
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130 if not_composite or not has_images:
131 for a in artists:
--> 132 a.draw(renderer)
133 else:
134 # Composite any adjacent images together
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49 renderer.start_filter()
50
---> 51 return draw(artist, renderer, *args, **kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\legend.py in draw(self, renderer)
612
613 self.legendPatch.draw(renderer)
--> 614 self._legend_box.draw(renderer)
615
616 renderer.close_group('legend')
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer)
366 for c, (ox, oy) in zip(self.get_visible_children(), offsets):
367 c.set_offset((px + ox, py + oy))
--> 368 c.draw(renderer)
369
370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer)
366 for c, (ox, oy) in zip(self.get_visible_children(), offsets):
367 c.set_offset((px + ox, py + oy))
--> 368 c.draw(renderer)
369
370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer)
366 for c, (ox, oy) in zip(self.get_visible_children(), offsets):
367 c.set_offset((px + ox, py + oy))
--> 368 c.draw(renderer)
369
370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer)
366 for c, (ox, oy) in zip(self.get_visible_children(), offsets):
367 c.set_offset((px + ox, py + oy))
--> 368 c.draw(renderer)
369
370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer)
692 if self._clip_children and not (c.clipbox or c._clippath):
693 c.set_clip_path(tpath)
--> 694 c.draw(renderer)
695
696 bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49 renderer.start_filter()
50
---> 51 return draw(artist, renderer, *args, **kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\collections.py in draw(self, renderer)
1007 def draw(self, renderer):
1008 self.set_sizes(self._sizes, self.figure.dpi)
-> 1009 super().draw(renderer)
1010
1011
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49 renderer.start_filter()
50
---> 51 return draw(artist, renderer, *args, **kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\collections.py in draw(self, renderer)
378 do_single_path_optimization = False
379 if (len(paths) == 1 and len(trans) <= 1 and
--> 380 len(facecolors) == 1 and len(edgecolors) == 1 and
381 len(self._linewidths) == 1 and
382 all(ls[1] is None for ls in self._linestyles) and
TypeError: object of type 'NoneType' has no len()
It seems to be an interaction with the c= for the coloring and the label=. If I comment out the color stuff (c=, cmap, colorbar), the plot renders with a legend box, and we saw that it also works with colors included and label commented out. I also tried restarting the kernel, and had same results. I have not tried making new environments with other versions yet, as I wanted to see if this was just me, or something others could replicate.
(BTW, On Colab, python 3.7.10, pandas 1.1.5, matplotlib 3.2.2, the code does appear to work (with a minor figsize complaint), so could be something about the more recent versions of these packages, or my setup...)
So, please be kind, but could anyone point out what silly thing I'm missing here? Any suggestions? Anyone able to replicate?
Possibly a bug in the older version, as it runs fine on recent versions of matplotlib. Recommend to just updating the matplotlib and pandas. Don't linger over it too much.
Related
Now I have one (1024, 1024) NumPy array named field which is stored in a .bigfile. And I want to visualize its values on the x-y plane by using plt.imshow. By the way, the minimum of field is 0.0, the maximum is 89297.414.Here is a snippet of this code.
# plot in the linuxremote server
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import bigfile
with bigfile.File('filename.bigfile') as bf:
shape = bf['Field'].attrs['ndarray.shape']
field = bf['Field'][:].reshape(shape)
plt.imshow(field, norm=mpl.colors.LogNorm());
plt.savefig('field.pdf')
After this code has run, ValueError:minvalue must be positive occured.
I guess that the the minimum value 0.0 caused the error, so I set field += 0.001. However, it is useless and the error still occurs.
ValueError Traceback (most recent call last)
<ipython-input-20-a10e1bbeb736> in <module>
----> 1 plt.savefig('field.pdf')
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/pyplot.py in savefig(*args, **kwargs)
841 def savefig(*args, **kwargs):
842 fig = gcf()
--> 843 res = fig.savefig(*args, **kwargs)
844 fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
845 return res
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/figure.py in savefig(self, fname, transparent, **kwargs)
2309 patch.set_edgecolor('none')
2310
-> 2311 self.canvas.print_figure(fname, **kwargs)
2312
2313 if transparent:
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2208
2209 try:
-> 2210 result = print_method(
2211 filename,
2212 dpi=dpi,
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/backend_bases.py in wrapper(*args, **kwargs)
1637 kwargs.pop(arg)
1638
-> 1639 return func(*args, **kwargs)
1640
1641 return wrapper
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/backends/backend_pdf.py in print_pdf(self, filename, dpi, bbox_inches_restore, metadata)
2591 RendererPdf(file, dpi, height, width),
2592 bbox_inches_restore=bbox_inches_restore)
-> 2593 self.figure.draw(renderer)
2594 renderer.finalize()
2595 if not isinstance(filename, PdfPages):
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
39 renderer.start_filter()
40
---> 41 return draw(artist, renderer, *args, **kwargs)
42 finally:
43 if artist.get_agg_filter() is not None:
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/figure.py in draw(self, renderer)
1861
1862 self.patch.draw(renderer)
-> 1863 mimage._draw_list_compositing_images(
1864 renderer, self, artists, self.suppressComposite)
1865
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
129 if not_composite or not has_images:
130 for a in artists:
--> 131 a.draw(renderer)
132 else:
133 # Composite any adjacent images together
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
39 renderer.start_filter()
40
---> 41 return draw(artist, renderer, *args, **kwargs)
42 finally:
43 if artist.get_agg_filter() is not None:
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py in wrapper(*inner_args, **inner_kwargs)
409 else deprecation_addendum,
410 **kwargs)
--> 411 return func(*inner_args, **inner_kwargs)
412
413 return wrapper
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2746 renderer.stop_rasterizing()
2747
-> 2748 mimage._draw_list_compositing_images(renderer, self, artists)
2749
2750 renderer.close_group('axes')
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
153 image_group.append(a)
154 else:
--> 155 flush_images()
156 a.draw(renderer)
157 flush_images()
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/image.py in flush_images()
139 image_group[0].draw(renderer)
140 elif len(image_group) > 1:
--> 141 data, l, b = composite_images(image_group, renderer, mag)
142 if data.size != 0:
143 gc = renderer.new_gc()
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/image.py in composite_images(images, renderer, magnification)
87 bboxes = []
88 for image in images:
---> 89 data, x, y, trans = image.make_image(renderer, magnification)
90 if data is not None:
91 x *= magnification
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/image.py in make_image(self, renderer, magnification, unsampled)
920 clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on()
921 else self.figure.bbox)
--> 922 return self._make_image(self._A, bbox, transformed_bbox, clip,
923 magnification, unsampled=unsampled)
924
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/image.py in _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification, unsampled, round_to_pixel_border)
539 vmax=vrange[1],
540 ):
--> 541 output = self.norm(resampled_masked)
542 else:
543 if A.shape[2] == 3:
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/colors.py in __call__(self, value, clip)
1190
1191 self.autoscale_None(result)
-> 1192 self._check_vmin_vmax()
1193 vmin, vmax = self.vmin, self.vmax
1194 if vmin == vmax:
/opt/miniconda3/lib/python3.8/site-packages/matplotlib/colors.py in _check_vmin_vmax(self)
1179 raise ValueError("minvalue must be less than or equal to maxvalue")
1180 elif self.vmin <= 0:
-> 1181 raise ValueError("minvalue must be positive")
1182
1183 def __call__(self, value, clip=None):
ValueError: minvalue must be positive
I ran this scatter plot seaborn example from their own website,
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# this works:
ax = sns.scatterplot(x="total_bill", y="tip", data=tips)
# But adding 'hue' gives the error below:
ax = sns.scatterplot(x="total_bill", y="tip", hue="time", data=tips)
This error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
e:\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)
e:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
246
247 if 'png' in formats:
--> 248 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
249 if 'retina' in formats or 'png2x' in formats:
250 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
e:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
130 FigureCanvasBase(fig)
131
--> 132 fig.canvas.print_figure(bytes_io, **kw)
133 data = bytes_io.getvalue()
134 if fmt == 'svg':
e:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2191 else suppress())
2192 with ctx:
-> 2193 self.figure.draw(renderer)
2194
2195 bbox_inches = self.figure.get_tightbbox(
e:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
39 renderer.start_filter()
40
---> 41 return draw(artist, renderer, *args, **kwargs)
42 finally:
43 if artist.get_agg_filter() is not None:
e:\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
1861
1862 self.patch.draw(renderer)
-> 1863 mimage._draw_list_compositing_images(
1864 renderer, self, artists, self.suppressComposite)
1865
e:\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
129 if not_composite or not has_images:
130 for a in artists:
--> 131 a.draw(renderer)
132 else:
133 # Composite any adjacent images together
e:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
39 renderer.start_filter()
40
---> 41 return draw(artist, renderer, *args, **kwargs)
42 finally:
43 if artist.get_agg_filter() is not None:
e:\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*inner_args, **inner_kwargs)
409 else deprecation_addendum,
410 **kwargs)
--> 411 return func(*inner_args, **inner_kwargs)
412
413 return wrapper
e:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
2746 renderer.stop_rasterizing()
2747
-> 2748 mimage._draw_list_compositing_images(renderer, self, artists)
2749
2750 renderer.close_group('axes')
e:\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
129 if not_composite or not has_images:
130 for a in artists:
--> 131 a.draw(renderer)
132 else:
133 # Composite any adjacent images together
e:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
39 renderer.start_filter()
40
---> 41 return draw(artist, renderer, *args, **kwargs)
42 finally:
43 if artist.get_agg_filter() is not None:
e:\Anaconda3\lib\site-packages\matplotlib\collections.py in draw(self, renderer)
929 def draw(self, renderer):
930 self.set_sizes(self._sizes, self.figure.dpi)
--> 931 Collection.draw(self, renderer)
932
933
e:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
39 renderer.start_filter()
40
---> 41 return draw(artist, renderer, *args, **kwargs)
42 finally:
43 if artist.get_agg_filter() is not None:
e:\Anaconda3\lib\site-packages\matplotlib\collections.py in draw(self, renderer)
383 else:
384 combined_transform = transform
--> 385 extents = paths[0].get_extents(combined_transform)
386 if (extents.width < self.figure.bbox.width
387 and extents.height < self.figure.bbox.height):
e:\Anaconda3\lib\site-packages\matplotlib\path.py in get_extents(self, transform, **kwargs)
601 xys.append(curve([0, *dzeros, 1]))
602 xys = np.concatenate(xys)
--> 603 return Bbox([xys.min(axis=0), xys.max(axis=0)])
604
605 def intersects_path(self, other, filled=True):
e:\Anaconda3\lib\site-packages\numpy\core\_methods.py in _amin(a, axis, out, keepdims, initial, where)
41 def _amin(a, axis=None, out=None, keepdims=False,
42 initial=_NoValue, where=True):
---> 43 return umr_minimum(a, axis, None, out, keepdims, initial, where)
44
45 def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
ValueError: zero-size array to reduction operation minimum which has no identity
Yesterday it did work. However, I ran an update of using conda update --all. Has something changed?
What's going on?
I run python on a Linux machine.
Pandas: 1.1.0.
Numpy: 1.19.1.
Seaborn api: 0.10.1.
This issue seems to be resolved for matplotlib==3.3.2.
seaborn: Scatterplot fails with matplotlib==3.3.1 #2194
With matplotlib version 3.3.1
A workaround is to send a list to hue, by using .tolist()
Use hue=tips.time.tolist().
The normal behavior adds a title to the legend, but sending a list to hue does not add the legend title.
The legend title can be added manually.
import seaborn as sns
# load data
tips = sns.load_dataset("tips")
# But adding 'hue' gives the error below:
ax = sns.scatterplot(x="total_bill", y="tip", hue=tips.time.tolist(), data=tips)
ax.legend(title='time') # add a title to the legend
I ran conda install -c conda-forge matplotlib==3.3.0 given known errors in 3.3.1.
A right answer, but not a great solution.
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)
I'm a bit new to python so bear with me. I'm having an issue with plotting. So I have a data set of latitudes, longitudes, elevations and concentrations over time. I'm trying to plot concentration vs time for each elevation at each unique latitude and longitude. Below is the code i have written to try to accomplish this (i have imported all necessary modules in code before this, the following is just the snippet of code that is giving me problems)
lat=df['Lat']
lat=lat.unique()
from matplotlib import axes
for a in range(0,len(lat)): #for unique latitude
current_lat=lat[a]
mask=df[['Lat']].isin([current_lat]).all(axis=1)
df1=df.ix[mask]
lon=df1['Lon']
lon=lon.unique()
for b in range(0,len(lon)):
current_lon=lon[b]
mask=df1[['Lon']].isin([current_lon]).all(axis=1)
df2=df1.ix[mask]
df2=df2.sort('El',axis=0)
elev=df2.El
elev=elev.unique()
plt.clf()
#d['lat,lon']=(current_lat,current_lon)
for c in range(0,len(elev)):
current_elev=elev[c]
mask=df2[['El']].isin([current_elev]).all(axis=1)
df3=df2.ix[mask]
df3=df3.sort()
if len(df3)>1:
x=df3.index
x=list(x)
y=list(df3.C)
fig=plt.figure(a+b+1)
ax=plt.subplot(111)
fig.set_size_inches(22,12,forward=True)
plt.plot(x,y,hold=True,label=current_elev)
plt.legend()
del_x=float(x_coord_release)-float(current_lat)
del_y=float(y_coord_release)-float(current_lon)
dist=round(math.sqrt(del_x**2+del_y**2),3)
textstr='Distance from release=\n%.2f\n'%(dist)
props=dict(boxstyle='round',facecolor='wheat',alpha=0.5)
#ax=plt.subplot(1,1,1)
xlim=ax.get_xbound()
ylim=ax.get_ybound()
ax.text(xlim[1],ylim[1],textstr,bbox=props)
ax.text(10,10,"Relative to Release Location",fontsize=9,color="black",bbox=dict(facecolor='wheat', alpha=0.5))
ax.set_title('Concentration vs Time based on Elevation at x={}, y={}'.format(int(round(float(current_lat),0)),int(round(float(current_lon),0))))
figure_name='Concentration vs Time based on Elevation at x={}, y={}'.format(int(round(float(current_lat),0)),int(round(float(current_lon),0)))
ax.set_xlabel('Time (min)')
ax.set_ylabel('Concentration (mg/m$^3$)')
fig.savefig(rdir+'\\'+figure_name+'.png',dpi=100)
#plt.show()
#plt.draw()
#raw_input('enter')
plt.close()
The error message/Traceback I'm getting is the following:
TypeError Traceback (most recent call last)
C:\Users\bhall\Documents\Scripts\MESO_plot_v2.py in <module>()
874 ax.set_xlabel('Time (min)')
875 ax.set_ylabel('Concentration (mg/m$^3$)')
--> 876 fig.savefig(rdir+'\\'+figure_name+'.png',dpi=100)
877 #plt.show()
878 #plt.draw()
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site- packages\matplotlib\figure.pyc in savefig(self, *args, **kwargs)
1474 self.set_frameon(frameon)
1475
-> 1476 self.canvas.print_figure(*args, **kwargs)
1477
1478 if frameon:
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site- packages\matplotlib\backends\backend_qt5agg.pyc in print_figure(self, *args, **kwargs)
159
160 def print_figure(self, *args, **kwargs):
--> 161 FigureCanvasAgg.print_figure(self, *args, **kwargs)
162 self.draw()
163
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
2209 orientation=orientation,
2210 bbox_inches_restore=_bbox_inches_restore,
-> 2211 **kwargs)
2212 finally:
2213 if bbox_inches and restore_bbox:
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
519
520 def print_png(self, filename_or_obj, *args, **kwargs):
--> 521 FigureCanvasAgg.draw(self)
522 renderer = self.get_renderer()
523 original_dpi = renderer.dpi
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.pyc in draw(self)
467
468 try:
--> 469 self.figure.draw(self.renderer)
470 finally:
471 RendererAgg.lock.release()
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
57 def draw_wrapper(artist, renderer, *args, **kwargs):
58 before(artist, renderer)
---> 59 draw(artist, renderer, *args, **kwargs)
60 after(artist, renderer)
61
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.pyc in draw(self, renderer)
1083 dsu.sort(key=itemgetter(0))
1084 for zorder, a, func, args in dsu:
-> 1085 func(*args)
1086
1087 renderer.close_group('figure')
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
57 def draw_wrapper(artist, renderer, *args, **kwargs):
58 before(artist, renderer)
---> 59 draw(artist, renderer, *args, **kwargs)
60 after(artist, renderer)
61
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_base.pyc in draw(self, renderer, inframe)
2108
2109 for zorder, a in dsu:
-> 2110 a.draw(renderer)
2111
2112 renderer.close_group('axes')
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
57 def draw_wrapper(artist, renderer, *args, **kwargs):
58 before(artist, renderer)
---> 59 draw(artist, renderer, *args, **kwargs)
60 after(artist, renderer)
61
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\text.pyc in draw(self, renderer)
640 renderer.draw_text(gc, x, y, clean_line,
641 self._fontproperties, angle,
--> 642 ismath=ismath, mtext=mtext)
643
644 gc.restore()
C:\Users\bhall\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.pyc in draw_text(self, gc, x, y, s, prop, angle, ismath, mtext)
204 #print x, y, int(x), int(y), s
205 self._renderer.draw_text_image(
--> 206 font.get_image(), np.round(x - xd), np.round(y + yd) + 1, angle, gc)
207
208 def get_text_width_height_descent(self, s, prop, ismath):
TypeError: Invalid input arguments to draw_text_image
It succesfully loops through several of the plots but keeps crashing on one plot and gives that error. I've tried just plotting that data manually and i have no issues so i'm at a loss as to what the problem/resolution is. Any help would be greatly appreciated!
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.