Basemap scatterplot, *c* parameter issue

Issue
I get an “Invalid rgb(a) arg” error, dealing with the c parameter for a basemap scatter plot. Problem is… this is not dissimilar to the one used (successfully) during a previous lesson in Data Cleaning Walkthrough: Analyzing and Visualizing the Data - 12. Plotting Percent Of English Learners by District.

Can you help me understand why I get this following error?

%matplotlib inline

districts = combined.groupby(["school_dist"]).agg(numpy.mean)
districts.reset_index(inplace=True)

from mpl_toolkits.basemap import Basemap

m = Basemap(projection='merc', llcrnrlat=40.496044, urcrnrlat=40.915256, llcrnrlon=-74.255735, urcrnrlon=-73.700272, resolution='i')

m.drawmapboundary(fill_color='#85A6D9')
m.drawcoastlines(color='#6D5F47', linewidth=.4)
m.drawrivers(color='#6D5F47', linewidth=.4)

longitudes = combined["lon"].tolist()
latitudes = combined["lat"].tolist()

m.scatter(longitudes, latitudes, s=50, zorder=2, latlon=True, c=districts["saf_tot_11"], cmap="summer")

pyplot.show()
ValueErrorTraceback (most recent call last)

/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgba(self, arg, alpha)
    367                     raise ValueError(
--> 368                             'length of rgba sequence should be either 3 or 4')
    369             else:


ValueError: length of rgba sequence should be either 3 or 4


During handling of the above exception, another exception occurred:


ValueErrorTraceback (most recent call last)

/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgba_array(self, c, alpha)
    398             # Single value? Put it in an array with a single row.
--> 399             return np.array([self.to_rgba(c, alpha)], dtype=np.float)
    400         except ValueError:


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgba(self, arg, alpha)
    375             raise ValueError(
--> 376                 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
    377 


ValueError: to_rgba: Invalid rgba arg "0     7.433333
1     7.520833
2     7.233333
3     7.714286
4     7.085714
5     7.660000
6     7.392308
7     7.218182
8     7.365000
9     7.268182
10    7.086667
11    7.666667
12    7.269231
13    7.435714
14    6.933333
15    6.325000
16    6.935714
17    7.109091
18    6.758333
19    7.620000
20    7.090909
21    7.850000
22    7.066667
23    7.753846
24    7.525000
25    7.140000
26    7.010000
27    7.463636
28    6.962500
29    7.577778
30    7.200000
31    7.383333
Name: saf_tot_11, dtype: float64"
length of rgba sequence should be either 3 or 4


During handling of the above exception, another exception occurred:


ValueErrorTraceback (most recent call last)

/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgb(self, arg)
    321                 raise ValueError(
--> 322                     'cannot convert argument to rgb sequence')
    323 


ValueError: cannot convert argument to rgb sequence


During handling of the above exception, another exception occurred:


ValueErrorTraceback (most recent call last)

/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgba(self, arg, alpha)
    369             else:
--> 370                 r, g, b = self.to_rgb(arg)
    371             if alpha is None:


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgb(self, arg)
    327             raise ValueError(
--> 328                 'to_rgb: Invalid rgb arg "%s"\n%s' % (str(arg), exc))
    329             # Error messages could be improved by handling TypeError


ValueError: to_rgb: Invalid rgb arg "7.433333333333333"
cannot convert argument to rgb sequence


During handling of the above exception, another exception occurred:


ValueErrorTraceback (most recent call last)

<ipython-input-13-58ad67afcb19> in <module>()
     15 latitudes = combined["lat"].tolist()
     16 
---> 17 m.scatter(longitudes, latitudes, s=50, zorder=2, latlon=True, c=districts["saf_tot_11"], cmap="summer")
     18 
     19 pyplot.show()


/dataquest/system/env/python3/lib/python3.4/site-packages/mpl_toolkits/basemap/__init__.py in with_transform(self, x, y, *args, **kwargs)
    566             # convert lat/lon coords to map projection coords.
    567             x, y = self(x,y)
--> 568         return plotfunc(self,x,y,*args,**kwargs)
    569     return with_transform
    570 


/dataquest/system/env/python3/lib/python3.4/site-packages/mpl_toolkits/basemap/__init__.py in scatter(self, *args, **kwargs)
   3254         self._save_use_hold(ax, kwargs)
   3255         try:
-> 3256             ret =  ax.scatter(*args, **kwargs)
   3257         finally:
   3258             self._restore_hold(ax)


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1810                     warnings.warn(msg % (label_namer, func.__name__),
   1811                                   RuntimeWarning, stacklevel=2)
-> 1812             return func(ax, *args, **kwargs)
   1813         pre_doc = inner.__doc__
   1814         if pre_doc is None:


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   3891                 offsets=offsets,
   3892                 transOffset=kwargs.pop('transform', self.transData),
-> 3893                 alpha=alpha
   3894                 )
   3895         collection.set_transform(mtransforms.IdentityTransform())


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/collections.py in __init__(self, paths, sizes, **kwargs)
    829         """
    830 
--> 831         Collection.__init__(self, **kwargs)
    832         self.set_paths(paths)
    833         self.set_sizes(sizes)


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/collections.py in __init__(self, edgecolors, facecolors, linewidths, linestyles, antialiaseds, offsets, transOffset, norm, cmap, pickradius, hatch, urls, offset_position, zorder, **kwargs)
    115 
    116         self.set_edgecolor(edgecolors)
--> 117         self.set_facecolor(facecolors)
    118         self.set_linewidth(linewidths)
    119         self.set_linestyle(linestyles)


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/collections.py in set_facecolor(self, c)
    610             c = mpl.rcParams['patch.facecolor']
    611         self._facecolors_original = c
--> 612         self._facecolors = mcolors.colorConverter.to_rgba_array(c, self._alpha)
    613         self.stale = True
    614 


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgba_array(self, c, alpha)
    420             result = np.zeros((nc, 4), dtype=np.float)
    421             for i, cc in enumerate(c):
--> 422                 result[i] = self.to_rgba(cc, alpha)
    423             return result
    424 


/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/colors.py in to_rgba(self, arg, alpha)
    374         except (TypeError, ValueError) as exc:
    375             raise ValueError(
--> 376                 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
    377 
    378     def to_rgba_array(self, c, alpha=None):


ValueError: to_rgba: Invalid rgba arg "7.433333333333333"
to_rgb: Invalid rgb arg "7.433333333333333"
cannot convert argument to rgb sequence

Link
Guided Project: Analyzing NYC High School Data - 2. Exploring Safety and SAT Scores

Hi sarang.rk,

I just had the same problem and realized where I went wrong. You’re pulling the longitudes and latitudes from the wrong dataframe.

change:
longitudes = combined[“lon”].tolist()
latitudes = combined[“lat”].tolist()

to:
longitudes = districts.lon.tolist()
latitudes = districts.lat.tolist()

I hope this helps and welcome to the community!
Leo

2 Likes

I spent over 5 hours trying to download basemap without success only to discover that it has been deprecated and replaced by cartoPy.

I will advise you modify the mission, ‘Visualizing geo data’ to align with cartoPy

3 Likes

Above is the link about basecamp deprecation, replaced with cartoPy.

I completely agree that the mission needs to be updated. Please take note, Dataquest! Getting basemap to work was a real P.I.T.A. -

2 Likes