Matplotlib代号

RSH*_*HAP 2 python matplotlib ticker

有人可以给我一个如何使用以下tickFormatters的示例。这些文档对我而言无益。

ticker.StrMethodFormatter() ticker.IndexFormatter()

例如,我可能会认为

x = np.array([ 316566.962,  294789.545,  490032.382,  681004.044,  753757.024,
            385283.153,  651498.538,  937628.225,  199561.358,  601465.455])
y = np.array([ 208.075,  262.099,  550.066,  633.525,  612.804,  884.785,
            862.219,  349.805,  279.964,  500.612])
money_formatter = tkr.StrMethodFormatter('${:,}')

plt.scatter(x,y)
ax = plt.gca()
fmtr = ticker.StrMethodFormatter('${:,}')
ax.xaxis.set_major_formatter(fmtr)
Run Code Online (Sandbox Code Playgroud)

会将我的刻度标签设置为美元符号,并用逗号分隔数千个地方的ala

['$300,000', '$400,000', '$500,000', '$600,000', '$700,000', '$800,000', '$900,000']
Run Code Online (Sandbox Code Playgroud)

但是我却得到了索引错误。

IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)

对于IndexFormatter文档说:

从标签列表中设置字符串

我真的不知道这意味着什么,当我尝试使用它时,抽动症消失了。

Imp*_*est 5

StrMethodFormatter通过提供可使用的格式化字符串确实工作format方法。因此,使用方法'${:,}'朝着正确的方向发展。

但是,从文档中我们可以了解到

用于值的字段必须标记为x,并且用于位置的字段必须标记为pos。

这意味着您需要x为该字段提供实际的标签。另外,您可能希望将数字格式指定为g不带小数点。

fmtr = matplotlib.ticker.StrMethodFormatter('${x:,g}')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

IndexFormatter这里没什么用。如您所知,您将需要提供标签列表。这些标签用于索引,从0开始。因此,使用此格式化程序将需要使x轴从零开始并在一些整数范围内。

例:

plt.scatter(range(len(y)),y)
fmtr = matplotlib.ticker.IndexFormatter(list("ABCDEFGHIJ"))
ax.xaxis.set_major_formatter(fmtr)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在这里,刻度线位于,(0,2,4,6,....)列表(A, C, E, G, I, ...)中的各个字母用作标签。