有色相影响的标记

2024-09-24 00:35:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让我的swarmplot在黑白和色盲的人中更容易阅读,通过让色调影响颜色,同时也影响标记的另一个几何方面。在

MWE公司

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()

结果

enter image description here

期望结果(左)

enter image description here


Tags: 标记importmatplotlib颜色as公司pltseaborn
3条回答

下面将提供一种方法,它可以轻松地为swarmplot获得所需的不同标记(或者更普遍地说是任何分类散点图)。它可以按原样使用,只需将其复制到现有的绘图脚本上即可。在

这个想法是把一个散点的颜色和一个标记联系起来。E、 任何散点都会自动从指定列表中获取标记。因此,这只适用于不同颜色的地块。在

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

############## Begin hack ##############
class CM():
    def __init__(self, markers=["o"]):
        self.marker = np.array(markers)
        self.colors = []

    def get_markers_for_colors(self, c):
        for _co in c:
            if not any((_co == x).all() for x in self.colors):
                self.colors.append(_co)
        ind = np.array([np.where((self.colors == row).all(axis=1)) \
                        for row in c]).flatten()
        return self.marker[ind % len(self.marker)]

    def get_legend_handles(self, **kwargs):
        return [plt.Line2D([0],[0], ls="none", marker=m, color=c, mec="none", **kwargs) \
                for m,c in zip(self.marker, self.colors)]

from matplotlib.axes._axes import Axes
import matplotlib.markers as mmarkers
cm = CM(plt.Line2D.filled_markers)
old_scatter = Axes.scatter
def new_scatter(self, *args, **kwargs):
    sc = old_scatter(self, *args, **kwargs)
    c = kwargs.get("c", None)
    if isinstance(c, np.ndarray):
        m = cm.get_markers_for_colors(c)
        paths = []
        for _m in m:
            marker_obj = mmarkers.MarkerStyle(_m)
            paths.append(marker_obj.get_path().transformed(
                        marker_obj.get_transform()))
        sc.set_paths(paths)
    return sc

Axes.scatter = new_scatter
############## End hack. ##############
# Copy and past to your file ##########


## Code ###

sns.set(style="whitegrid")
tips = sns.load_dataset("tips")

fig, ax = plt.subplots(1,1)
## Optionally specify own markers:
#cm.marker = np.array(["^", "s"])
ax = sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips,size=8,ax=ax)

## Optionally adjust legend:
_,l = ax.get_legend_handles_labels()
ax.legend(cm.get_legend_handles(markersize=8),l)

plt.show()

enter image description here

其实我之前也想过同样的问题。我没有想出最好的解决方案,但我有一个黑客,工作正常。不幸的是,如果使用dodge=True,则实现起来要容易得多。在

其思想是收集由swarmplot创建的PathCollections对象。如果dodge=True,那么您将得到N_cat*N_hues+N_hues个集合(N_hues extra用于创建图例)。您可以简单地遍历该列表。因为我们希望所有的色调都是相同的,所以我们使用N_hues步幅来获得与每个色调对应的所有集合。之后,您可以将该集合的paths更新为您选择的任何Path对象。请参阅the documentation for ^{}以了解如何创建路径。在

为了简化操作,我在手之前创建了一些虚拟的散点图,以获得一些可以使用的预制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()

enter image description here

更新dodge=False“合作”的解决方案。在

如果使用dodge=False,那么将得到N+2个集合,每个类别一个,图例+2个。问题是所有不同的标记颜色在这些集合中都是混乱的。在

一个可能的,但很难看的解决方案是循环访问集合的每个元素,并基于每个元素的颜色创建一个Path对象的数组。在

^{pr2}$

enter image description here

感谢@ImportanceOfBeingErnest提供解决方案。我试图编辑他/她的解决方案来解决一些小问题,但最终他/她建议我发布自己的答案。在

这个解决方案和他/她的一样,但是当没有指定标记阵列时,它不会改变法向散射的行为。它的应用也更简单,它修复了图例失去标题的错误。在

下图由以下代码生成:

enter image description here

import seaborn as sns
import matplotlib.pyplot as plt

############## Begin hack ##############
from matplotlib.axes._axes import Axes
from matplotlib.markers import MarkerStyle
from seaborn import color_palette
from numpy import ndarray

def GetColor2Marker(markers):
    palette = color_palette()
    mkcolors = [(palette[i]) for i in range(len(markers))]
    return dict(zip(mkcolors,markers))

def fixlegend(ax,markers,markersize=8,**kwargs):
    # Fix Legend
    legtitle =  ax.get_legend().get_title().get_text()
    _,l = ax.get_legend_handles_labels()
    palette = color_palette()
    mkcolors = [(palette[i]) for i in range(len(markers))]
    newHandles = [plt.Line2D([0],[0], ls="none", marker=m, color=c, mec="none", markersize=markersize,**kwargs) \
                for m,c in zip(markers, mkcolors)]
    ax.legend(newHandles,l)
    leg = ax.get_legend()
    leg.set_title(legtitle)

old_scatter = Axes.scatter
def new_scatter(self, *args, **kwargs):
    colors = kwargs.get("c", None)
    co2mk = kwargs.pop("co2mk",None)
    FinalCollection = old_scatter(self, *args, **kwargs)
    if co2mk is not None and isinstance(colors, ndarray):
        Color2Marker = GetColor2Marker(co2mk)
        paths=[]
        for col in colors:
            mk=Color2Marker[tuple(col)]
            marker_obj = MarkerStyle(mk)
            paths.append(marker_obj.get_path().transformed(marker_obj.get_transform()))
        FinalCollection.set_paths(paths)
    return FinalCollection
Axes.scatter = new_scatter
############## End hack. ##############


# Example Test 
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")

# To test robustness
tips.loc[(tips['sex']=="Male") & (tips['day']=="Fri"),'sex']='Female'
tips.loc[(tips['sex']=="Female") & (tips['day']=="Sat"),'sex']='Male'

Markers = ["o","P"]

fig, axs = plt.subplots(1,2,figsize=(14,5))
axs[0] = sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips,size=8,ax=axs[0])
axs[0].set_title("Original")
axs[1] = sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips,size=8,ax=axs[1],co2mk=Markers)
axs[1].set_title("Hacked")
fixlegend(axs[1],Markers)

plt.show()

相关问题 更多 >