gpt4 book ai didi

matplotlib - FacetGrid 图例为空

转载 作者:行者123 更新时间:2023-12-01 12:36:41 25 4
gpt4 key购买 nike

我正在尝试创建一个 seaborn FacetGrid 来显示我拥有的某些数据中集群之间的转换概率。数据有一堆主题和 4 个集群(因此每个主题有 16 个数据点,每对新旧集群一个)。因为这些是概率,所以所有具有相同旧聚类(对于每个主题)的值总和为 1。我想使用 FacetGrid 点图(或堆叠条形图,但对于 seaborn 似乎不可能)显示这些数据,例如每个旧集群是一个单独的列,新集群是一个单独的色调,每个方面都显示主题与概率。

这是生成具有与我的功能相同的玩具 DataFrame 的代码,以及我想要制作的 facetgrid 的代码。然而,当我做这一切时,传说是空的。

df,index = [],0
for subj in [1,2]:
for i,j in itertools.product(range(4),range(4)):
df.append(pd.DataFrame(index=[index],data=dict(subject=subj,old=i,new=j,prob=[.23,.24,.26,.27][j])))
index+=1
df = pd.concat(df)
g = sns.FacetGrid(df,col='old',hue='new',margin_titles=False,legend_out=True)
g.map(sns.pointplot,'subject','prob',join=False)
g.add_legend()

查看 g._legend_data 表明它是空的,并且每个轴 get_legend_handles_labels() 函数都不返回任何内容。这是怎么回事?

我不能张贴我的情节图片,因为我没有 10 声望;传说的名字出现在最右边,但里面什么都没有……

编辑 :此外,我想稍微避开这些值,但 g.map(sns.pointplot,'subject','prob',join=False,dodge=.1) 看起来与上面完全相同,对于各种不同的闪避值...

编辑 2: 所以看起来使用 sns.factorplot 而不是 FacetGrid,图例和闪避都有效。我唯一不能使用 sns.factorplot 做的事情是旋转 xtick 标签,但这无论如何都不适用于 Facet Grid 中的 col_wrap ......为什么 FacetGrid 有这个问题?

最佳答案

正如您所注意到的,factorplot 提供了一个更简单的界面来一起使用 pointplotFacetGrid。图例和闪避不能按照您原来的方式工作的原因是在 hue 中设置 FacetGrid 和在 pointplot 中设置它是不同的。当你在没有pointplot变量的情况下调用hue时,它不知道如何闪避,它认为它不需要添加任何图例数据。

选项一是移动使用 hue 变量的位置:

g = sns.FacetGrid(df,col='old', col_wrap=2)
g.map(sns.pointplot, 'subject', 'prob', 'new', dodge=.1, join=False)
g.add_legend()

但我想不出有任何理由以这种方式使用 FacetGrid 而不是仅使用 factorplot :
g = sns.factorplot(x="subject", y="prob", hue="new", data=df,
col="old", col_wrap=2, size=3,
dodge=.1, join=False)

所以唯一剩下的问题是旋转 x 轴刻度标签。 factorplot 返回一个 FacetGrid 实例,因此原则上应该很容易使用进一步的 FacetGrid 方法来调整绘图。我怀疑您遇到的问题是 this bug ,它将在下一个版本中修复。同时,您可以像这样解决它:
g = sns.factorplot(x="subject", y="prob", hue="new", data=df,
col="old", col_wrap=2, size=3,
dodge=.1, join=False)
for ax in g.axes:
plt.setp(ax.get_xticklabels(), rotation=45)

关于matplotlib - FacetGrid 图例为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28992174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com