指定刻度标签的浮点格式
- 2025-01-22 08:45:00
- admin 原创
- 83
问题描述:
我正在尝试在 matplotlib 子图环境中将格式设置为两个十进制数。不幸的是,我不知道如何解决这个任务。
为了避免在 y 轴上使用科学记数法,我使用了ScalarFormatter(useOffset=False)
下面的代码片段。我认为我的任务应该通过向使用的格式化程序传递更多选项/参数来解决。但是,我在 matplotlib 的文档中找不到任何提示。
我如何设置两位小数或无小数(两种情况都需要)?遗憾的是,我无法提供样本数据。
-- 摘录 --
f, axarr = plt.subplots(3, sharex=True)
data = conv_air
x = range(0, len(data))
axarr[0].scatter(x, data)
axarr[0].set_ylabel('$T_mathrm{air,2,2}$', size=FONT_SIZE)
axarr[0].yaxis.set_major_locator(MaxNLocator(5))
axarr[0].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[0].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[0].grid(which='major', alpha=0.5)
axarr[0].grid(which='minor', alpha=0.2)
data = conv_dryer
x = range(0, len(data))
axarr[1].scatter(x, data)
axarr[1].set_ylabel('$T_mathrm{dryer,2,2}$', size=FONT_SIZE)
axarr[1].yaxis.set_major_locator(MaxNLocator(5))
axarr[1].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[1].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[1].grid(which='major', alpha=0.5)
axarr[1].grid(which='minor', alpha=0.2)
data = conv_lambda
x = range(0, len(data))
axarr[2].scatter(x, data)
axarr[2].set_xlabel('Iterationsschritte', size=FONT_SIZE)
axarr[2].xaxis.set_major_locator(MaxNLocator(integer=True))
axarr[2].set_ylabel('$lambda$', size=FONT_SIZE)
axarr[2].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[2].yaxis.set_major_locator(MaxNLocator(5))
axarr[2].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[2].grid(which='major', alpha=0.5)
axarr[2].grid(which='minor', alpha=0.2)
解决方案 1:
请参阅相关文献,具体如下:
from matplotlib.ticker import FormatStrFormatter
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
解决方案 2:
如果你直接使用 matplotlib 的 pyplot (plt),并且熟悉新式格式字符串,则可以尝试以下操作:
from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
来自文档:
类 matplotlib.ticker.StrMethodFormatter(fmt)
使用新样式的格式字符串(如 str.format() 所使用的)来格式化刻度。
用于值的字段必须标记为 x,用于位置的字段必须标记为 pos。
解决方案 3:
上述答案可能是正确的方法,但对我来说不起作用。
为我解决这个问题的黑客方法如下:
ax = <whatever your plot is>
# get the current labels
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family
plt.show()
解决方案 4:
使用 lambda 函数格式化标签
3x 同一图,但 y 轴标签不同
最小示例
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
from matplotlib.ticker import FormatStrFormatter
fig, axs = mpl.pylab.subplots(1, 3)
xs = np.arange(10)
ys = 1 + xs ** 2 * 1e-3
axs[0].set_title('default y-labeling')
axs[0].scatter(xs, ys)
axs[1].set_title('custom y-labeling')
axs[1].scatter(xs, ys)
axs[2].set_title('x, pos arguments')
axs[2].scatter(xs, ys)
fmt = lambda x, pos: '1+ {:.0f}e-3'.format((x-1)*1e3, pos)
axs[1].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))
fmt = lambda x, pos: 'x={:f}
pos={:f}'.format(x, pos)
axs[2].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))
当然,你也可以使用“真实”函数代替 lambda。https
://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html
解决方案 5:
在 matplotlib 3.1 中,您还可以使用ticklabel_format。为了防止没有偏移量的科学计数法:
plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD