其实我之前也想过同样的问题。我没有想出最好的解决方案,但我有一个可以正常工作的 hack。不幸的是,如果你使用dodge=True,它会更容易实现。
这个想法是收集swarmplot创建的PathCollections对象。如果dodge=True,那么您将获得N_cat*N_hues+N_hues 集合(N_hues 额外用于创建图例)。您可以简单地遍历该列表。由于我们希望所有色调都相同,因此我们使用 N_hues 步长来获取与每种色调对应的所有集合。之后,您可以随意将该集合的paths 更新为您选择的任何Path 对象。参考the documentation for Path了解如何创建路径。
为了简化事情,我在手之前创建了一些虚拟散点图,以获得一些我可以使用的预制Paths。当然,任何Path 都应该可以工作。
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
fig, ax = plt.subplots(1,1)
# dummy plots, just to get the Path objects
a = ax.scatter([1,2],[3,4], marker='s')
b = ax.scatter([1,2],[3,4], marker='^')
square_mk, = a.get_paths()
triangle_up_mk, = b.get_paths()
a.remove()
b.remove()
ax = sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips,size=8,ax=ax, dodge=True)
N_hues = len(pd.unique(tips.sex))
c = ax.collections
for a in c[::N_hues]:
a.set_paths([triangle_up_mk])
for a in c[1::N_hues]:
a.set_paths([square_mk])
#update legend
ax.legend(c[-2:],pd.unique(tips.sex))
plt.show()
更新与dodge=False“工作”的解决方案。
如果您使用dodge=False,那么您将获得 N+2 个集合,每个类别一个,图例 +2。问题是这些集合中所有不同的标记颜色都混杂在一起。
一个可能但丑陋的解决方案是遍历集合的每个元素,并根据每个元素的颜色创建一个 Path 对象数组。
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
fig, ax = plt.subplots(1,1)
ax = sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips,size=8,ax=ax, dodge=False)
collections = ax.collections
unique_colors = np.unique(collections[0].get_facecolors(), axis=0)
markers = [triangle_up_mk, square_mk] # this array must be at least as large as the number of unique colors
for collection in collections:
paths = []
for current_color in collection.get_facecolors():
for possible_marker,possible_color in zip(markers, unique_colors):
if np.array_equal(current_color,possible_color):
paths.append(possible_marker)
break
collection.set_paths(paths)
#update legend
ax.legend(collections[-2:],pd.unique(tips.sex))
plt.show()