谁能给我一个如何使用以下 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
['$300,000', '$400,000', '$500,000', '$600,000', '$700,000', '$800,000', '$900,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, ...)
用作标签。
关于python - Matplotlib 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187290/