Matplotlib 代码

Matplotlib Ticker

谁能给我一个如何使用以下 tickFormatters 的例子。 docs 对我来说没有意义。

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)

会将我的刻度标签设置为美元符号和逗号 sep 用于千位 ala

['0,000', '0,000', '0,000', '0,000', '0,000', '0,000', '0,000']

但是我得到了一个索引错误。

IndexError: tuple index out of range

对于 IndexFormatter 文档说:

Set the strings from a list of labels

我真的不知道这是什么意思,当我尝试使用它时,我的抽搐消失了。

StrMethodFormatter 通过提供可以使用 format 方法格式化的字符串确实有效。所以使用 '${:,}' 的方法是正确的。

但是从the documentation我们了解到

The field used for the value must be labeled x and the field used for the position must be labeled pos.

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

fmtr = matplotlib.ticker.StrMethodFormatter('${x:,g}')

IndexFormatter在这里用处不大。正如您所发现的,您需要提供标签列表。这些标签用于索引,从 0 开始。因此使用此格式化程序需要使 x 轴从零开始并在一些整数范围内。

示例:

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

此处,刻度位于 (0,2,4,6,....),列表 (A, C, E, G, I, ...) 中的相应字母用作标签。