如何在 Seaborn 中使用 Facet Grid 用逗号分隔千位

How to separate thousands with commas using Facet Grid in Seaborn

我有以下代码:

    d = sns.FacetGrid(data = df,
                      col = 'Company',
                      sharex = False,
                      sharey = False,
                      col_wrap = 4)
    d.map(sns.distplot, 'Volume', kde = False, rug = True, fit = stats.norm)
    d.set_xlabels('volume')
    d.set_xticklabels(rotation = 45)
    plt.savefig(myDataRepository + 'figure_02__' + str(time_stamp) + '.png')
    ax.get_xaxis().set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

最后两行尝试用逗号分隔 x 轴值。例如,“500,000”而不是“500000”。

我看到一条错误消息:

"global name ax is not defined"

我将如何修改 ax. 以便我可以用逗号分隔格式化 x 轴值?

提前致谢!

---编辑如下---

这是我发布的更新代码。它仍然失败,但这次在评估

时出现错误消息 @property
d.ax.get_xaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: format(int(x), ',')))

修改后的代码:

fig, ax = plt.subplots()

d = sns.FacetGrid(data = df,
                  col = 'Company',
                  sharex = False,
                  sharey = False,
                  col_wrap = 4)
d.map(sns.distplot, 'Volume', kde = False, rug = True, fit = stats.norm)
d.set_xlabels('volume')
d.set_xticklabels(rotation = 45)
plt.savefig(myDataRepository + 'figure_02__' + str(time_stamp) + '.png')

d.ax.get_xaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: format(int(x), ',')))

@cphlewis 建议我将 ax.get_axis() 放在 Facet Grid 中。但是怎么办???

ax.get_axis() 放入 FacetGrid 中似乎无法解决此问题(假设我这样做是正确的)。甚至 可能 将此 ax.get_axis() 函数与 Seaborn FacetGrid 一起使用吗?

错误信息:

    971             return self.axes[0, 0]
    972         else:
--> 973             raise AttributeError
    974 
    975     @property

AttributeError: 

指定ax里面的FacetGrid:

df = random((5, 5))
d = sns.FacetGrid(data=df)
dir(d.ax.get_xaxis())

啊哈,get_major_formatter 在该列表中。

我也遇到了这个问题,通过添加一个简单的循环来用逗号格式化所有轴,在这里想出了一个干净的解决方案。

# set up the standard plotting of the df
g = sns.PairGrid(wmix, vars = ['ambulatory', 'wheelchair', 'stretcher'], hue="holiday")

g.map_upper(plt.scatter)
g.map_lower(sns.kdeplot)
g.map_diag(sns.kdeplot, lw=2, legend=False)
g.add_legend()


# now add the comma and remove decimal formats for each y axis
for ax in g.axes[:,0]:
  ax.get_yaxis().set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

# this adds the axis labels to each plot
plt.subplots_adjust(top=0.9)
g.fig.suptitle('Ride Count Relationships');