Mig*_*uel 4 python plot seaborn swarmplot
我试图让我的群图更容易以黑白方式阅读,并且对于色盲的人来说,通过让色调不仅影响颜色,还影响标记的另一个几何方面。
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)
plt.show()
Run Code Online (Sandbox Code Playgroud)
其实我不久前也想过同样的问题。我没有想出最好的解决方案,但我有一个可以正常工作的技巧。不幸的是,如果您使用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()
Run Code Online (Sandbox Code Playgroud)
更新一个与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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6817 次 |
| 最近记录: |