Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a list of marker styles in matplotlib?

I am working on plotting a 5D visualization using matplotlib.

I am trying to display different markers in my scatterplot based on an arbitrary threshold which I am basing off of a condition whose values I am assigning to a variable which I am using to pass into my call to ax.scatter(..., marker=markers).

My issue is, that although I am implementing the same solution in a separate plot successfully, in this case I am getting an Unrecognized marker error.

Here is the code I am trying to implement:

markers = ['o' if ub > 1.0 else 's' for ub in list(zScoreXsigVIF['mwntd'])]

# Plot DataFrame scatter plot
ax.scatter(zScoreXsigVIF[resid.price >= 0].trvou, zScoreXsigVIF[resid.price >= 0].demand, zScoreY[resid.price >= 0], color='black', alpha=1.0, facecolor='white', s=ss, marker=markers)

Here is the Error I am getting in Jupyter Lab:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
c:\program files\python36\lib\site-packages\matplotlib\markers.py in set_marker(self, marker)
    267             try:
--> 268                 Path(marker)
    269                 self._marker_function = self._set_vertices

c:\program files\python36\lib\site-packages\matplotlib\path.py in __init__(self, vertices, codes, _interpolation_steps, closed, readonly)
    131         """
--> 132         vertices = _to_unmasked_float_array(vertices)
    133         if (vertices.ndim != 2) or (vertices.shape[1] != 2):

c:\program files\python36\lib\site-packages\matplotlib\cbook\__init__.py in _to_unmasked_float_array(x)
   2049     else:
-> 2050         return np.asarray(x, float)
   2051 

c:\program files\python36\lib\site-packages\numpy\core\numeric.py in asarray(a, dtype, order)
    491     """
--> 492     return array(a, dtype, copy=False, order=order)
    493 

ValueError: could not convert string to float: 's'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-261-78858d0a01f7> in <module>()
     18 
     19 # Plot DataFrame scatter plot
---> 20 ax.scatter(zScoreXsigVIF[resid.price >= 0].trvou, zScoreXsigVIF[resid.price >= 0].demand, zScoreY[resid.price >= 0], color='black', alpha=1.0, facecolor='white', s=ss, marker=markers)
     21 ax.scatter(zScoreXsigVIF[resid.price < 0].trvou, zScoreXsigVIF[resid.price < 0].demand, zScoreY[resid.price < 0], color='black', alpha=1.0, s=ss, marker=markers)
     22 

c:\program files\python36\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py in scatter(self, xs, ys, zs, zdir, s, c, depthshade, *args, **kwargs)
   2360 
   2361         patches = super(Axes3D, self).scatter(
-> 2362             xs, ys, s=s, c=c, *args, **kwargs)
   2363         is_2d = not cbook.iterable(zs)
   2364         zs = _backports.broadcast_to(zs, len(xs))

c:\program files\python36\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
   1853                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1854                         RuntimeWarning, stacklevel=2)
-> 1855             return func(ax, *args, **kwargs)
   1856 
   1857         inner.__doc__ = _add_data_doc(inner.__doc__,

c:\program files\python36\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4301             marker_obj = marker
   4302         else:
-> 4303             marker_obj = mmarkers.MarkerStyle(marker)
   4304 
   4305         path = marker_obj.get_path().transformed(

c:\program files\python36\lib\site-packages\matplotlib\markers.py in __init__(self, marker, fillstyle)
    187         self._marker_function = None
    188         self.set_fillstyle(fillstyle)
--> 189         self.set_marker(marker)
    190 
    191     def __getstate__(self):

c:\program files\python36\lib\site-packages\matplotlib\markers.py in set_marker(self, marker)
    270             except ValueError:
    271                 raise ValueError('Unrecognized marker style'
--> 272                                  ' {0}'.format(marker))
    273 
    274         self._marker = marker

ValueError: Unrecognized marker style ['s', 's', 's']

What am I doing wrong with the values in my markers that is causing this error?

like image 294
lopezdp Avatar asked Mar 05 '23 15:03

lopezdp


1 Answers

It is currently not possible to supply a list of markers to the marker argument of scatter.

A workaround is to define a custom scatter function like this:

import matplotlib.pyplot as plt

def mscatter(x,y,z, ax=None, m=None, **kw):
    import matplotlib.markers as mmarkers
    ax = ax or plt.gca()
    sc = ax.scatter(x,y,z,**kw)
    if (m is not None) and (len(m)==len(x)):
        paths = []
        for marker in m:
            if isinstance(marker, mmarkers.MarkerStyle):
                marker_obj = marker
            else:
                marker_obj = mmarkers.MarkerStyle(marker)
            path = marker_obj.get_path().transformed(
                        marker_obj.get_transform())
            paths.append(path)
        sc.set_paths(paths)
    return sc

which you can use as

from mpl_toolkits.mplot3d import Axes3D    

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

xs = [1,2,3]
ys = [2,4,1]
zs = [1,5,2]
c = [250,600,400]
m = ["s", "o", "d"]

mscatter(xs, ys, zs, ax=ax, m=m, c=c, s=100)

plt.show()

enter image description here

like image 69
ImportanceOfBeingErnest Avatar answered Mar 08 '23 13:03

ImportanceOfBeingErnest