programing

눈금 레이블에 대한 부동 소수점 형식 지정

cafebook 2023. 7. 22. 10:23
반응형

눈금 레이블에 대한 부동 소수점 형식 지정

matplotlib 하위 플롯 환경에서 형식을 소수점 두 개로 설정하려고 합니다.안타깝게도, 저는 이 과제를 어떻게 해결해야 할지 전혀 모르겠습니다.

사용한 y축에 과학적 표기법 사용을 방지하기 위해ScalarFormatter(useOffset=False)아래의 제 스니펫에서 볼 수 있듯이.저는 사용된 포맷터에 추가 옵션/인수를 전달함으로써 제 과제를 해결해야 한다고 생각합니다.하지만 matplotlib의 문서에서 힌트를 찾을 수 없었습니다.

10진수를 두 자리로 설정하거나 0자리로 설정하지 않는 방법은 무엇입니까(두 자리 모두 필요)?유감스럽게도 샘플 데이터를 제공할 수 없습니다.


코드 조각 --

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)

일반적으로 그리고 구체적으로 관련 문서를 참조

from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

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

enter image description here

matplotlib의 파이플롯(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

설명서에서 다음을 참조하십시오.

클래스 매트플롯립.간지러운Str 메서드 포맷터(fmt)

str.format()에서 사용하는 새 형식 문자열을 사용하여 눈금 형식을 지정합니다.

값에 사용되는 필드에는 x 레이블이 지정되고 위치에 사용되는 필드에는 pos 레이블이 지정되어야 합니다.

위의 답변은 아마도 올바른 방법일 것입니다만, 저에게는 효과가 없었습니다.

저를 위해 그것을 해결한 해박한 방법은 다음과 같습니다.

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

람다 함수를 사용하여 레이블 형식 지정

enter image description here 3배 동일한 그림(다각형 모형 포함)

최소 예제

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}\npos={:f}'.format(x, pos)
axs[2].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))

물론 람다 대신 '진짜' 기능을 사용할 수도 있습니다.https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html

matplotlib 3.1에서는 ticklabel_format도 사용할 수 있습니다.오프셋이 없는 과학적 표기를 방지하려면:

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

언급URL : https://stackoverflow.com/questions/29188757/specify-format-of-floats-for-tick-labels

반응형