其实我之前也想过同样的问题。我没有想出最好的解决方案,但我有一个可以正常工作的 hack。不幸的是,如果您使用dodge=True
.
这个想法是收集PathCollections
由swarmplot
. 如果那样的dodge=True
话,您将获得N_cat*N_hues+N_hues
收藏(N_hues 附加功能用于创建图例)。您可以简单地遍历该列表。由于我们希望所有色调都相同,因此我们使用 N_hues 步长来获取与每种色调对应的所有集合。之后,您可以自由地paths
将该集合的更新为Path
您选择的任何对象。请参阅文档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()
