如何在matplotlib中添加标记样式列表?
问题描述
我正在使用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 filespython36libsite-packagesmatplotlibmarkers.py in set_marker(self, marker)
267 try:
--> 268 Path(marker)
269 self._marker_function = self._set_vertices
c:program filespython36libsite-packagesmatplotlibpath.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 filespython36libsite-packagesmatplotlibcbook\__init__.py in _to_unmasked_float_array(x)
2049 else:
-> 2050 return np.asarray(x, float)
2051
c:program filespython36libsite-packages
umpycore
umeric.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 filespython36libsite-packagesmpl_toolkitsmplot3daxes3d.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 filespython36libsite-packagesmatplotlib\__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 filespython36libsite-packagesmatplotlibaxes\_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 filespython36libsite-packagesmatplotlibmarkers.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 filespython36libsite-packagesmatplotlibmarkers.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']
我对标记中的值做错了什么导致此错误?
解决方案
currently not possible向scatter
的marker
参数提供标记列表。
解决方法是定义自定义散布函数,如下所示:
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
您可以将其用作
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()
相关文章