Passing list of colours to pandas .plot - python

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)

Related

shade area between 2 line plots ValueError: ordinal must be >= 1

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')

Why `ValueError: minvalue must be positive` occurred after that I run `plt.savefig()`?

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

ValueError in seaborn scatterplot with hue argument [duplicate]

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.

matplotlib how to plot multiple lines with defined colours?

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()

custom styles maplotlib (.mplstyle)

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.

Categories