web-dev-qa-db-ja.com

Matplotlib:目盛りラベルのfloatの形式を指定します

Matplotlibサブプロット環境でフォーマットを2つの10進数に設定しようとしています。残念ながら、このタスクを解決する方法はわかりません。

Y軸で科学表記法を使用しないようにするために、以下のスニペットでわかるようにScalarFormatter(useOffset=False)を使用しました。使用するフォーマッタにオプション/引数をさらに渡すことで、私のタスクを解決する必要があると思います。しかし、matplotlibのドキュメントにはヒントが見つかりませんでした。

2桁の10進数字を設定するか、何も設定しないのですか(両方のケースが必要です)。残念ながら、サンプルデータを提供することはできません。


-スニペット-

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)
40
albert

一般 および 具体的に の関連ドキュメントを参照してください

from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

enter image description here

77
tacaswell

上記の答えはおそらくそれを行う正しい方法ですが、私にとってはうまくいきませんでした。

私にとってそれを解決したハッキン​​グ方法は次のとおりでした:

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()
13
sapo_cosmico

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

ドキュメント から:

class matplotlib.ticker.StrMethodFormatter(fmt)

新しいスタイルのフォーマット文字列(str.format()で使用される)を使用して、目盛りをフォーマットします。

値に使用するフィールドにはxのラベルを付け、位置に使用するフィールドにはposのラベルを付ける必要があります。

6
CodeWarrior

Matplotlib 3.1では、 ticklabel_format も使用できます。オフセットなしの科学表記法を防止するには:

plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)
0
foxpal