如何在matplotlib中添加标记样式列表?

时间:2018-08-12 16:00:15

标签: python matplotlib data-visualization jupyter-lab

我正在使用matplotlib绘制5D可视化图像。

我正在尝试根据一个任意阈值在散点图中显示不同的标记,该阈值基于我将其值分配给一个变量的条件,该变量正用于传递给我对ax.scatter(..., marker=markers)的调用。

我的问题是,尽管我成功地在单独的图中实现了相同的解决方案,但是在这种情况下,我却得到了Unrecognized marker error

这是我要实现的代码:

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)

这是我在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']

我的标记中导致该错误的值在做什么?

1 个答案:

答案 0 :(得分:2)

currently not possiblemarker的{​​{1}}参数提供了标记列表。

一种解决方法是定义一个自定义散点函数,如下所示:

scatter

您可以用作

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

enter image description here