Pandas 히스토그램의 y축에 백분율을 표시하는 방법


다음 기본 구문을 사용하여 Pandas 히스토그램의 y축에 백분율을 표시할 수 있습니다.

 import pandas as pd
import numpy as np
import matplotlib. pyplot as plt
from matplotlib. ticker import PercentFormatter

#create histogram, using percentages instead of counts
plt. hist (df[' my_column '], weights= np.ones ( len (df)) / len (df))

#apply percentage format to y-axis
plt. gca (). yaxis . set_major_formatter (PercentFormatter(1))
plt. show ()

다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.

예: Pandas 히스토그램의 Y축에 백분율 표시

다양한 농구 선수에 대한 정보가 포함된 다음과 같은 pandas DataFrame이 있다고 가정합니다.

 import pandas as pd
import numpy as np

#make this example reproducible
n.p. random . seeds (1)

#createDataFrame
df = pd. DataFrame ({' points ': np. random . normal (loc=20, scale=2, size=300),
                   ' assists ': np. random . normal (loc=14, scale=3, size=300),
                   ' rebounds ': np. random . normal (loc=12, scale=1, size=300)})

#view head of DataFrame
print ( df.head ())

      points assists rebounds
0 23.248691 20.197350 10.927036
1 18.776487 9.586529 12.495159
2 18.943656 11.509484 11.047938
3 17.854063 11.358267 11.481854
4 21.730815 13.162707 10.538596

포인트 열의 값 분포를 시각화하기 위해 히스토그램을 생성하면 기본적으로 y축에 개수가 표시됩니다.

 import matplotlib. pyplot as plt 

#create histogram for points columb
plt. hist (df[' points '], edgecolor=' black ')

대신 y축에 백분율을 표시하려면 PercentFormatter 함수를 사용할 수 있습니다.

 import numpy as np
import matplotlib. pyplot as plt
from matplotlib. ticker import PercentFormatter

#create histogram, using percentages instead of counts
plt. hist (df[' points '], weights=np. ones ( len (df)) / len (df), edgecolor=' black ')

#apply percentage format to y-axis
plt. gca (). yaxis . set_major_formatter (PercentFormatter(1))
plt. show () 

y 축에 백분율이 표시된 팬더 히스토그램

이제 Y축에 백분율이 표시됩니다.

백분율에서 소수 자릿수를 제거하려면 PercentFormatter() 함수에서 소수 = 0 인수를 사용하면 됩니다.

 import numpy as np
import matplotlib. pyplot as plt
from matplotlib. ticker import PercentFormatter

#create histogram, using percentages instead of counts
plt. hist (df[' points '], weights=np. ones ( len (df)) / len (df), edgecolor=' black ')

#apply percentage format to y-axis
plt. gca (). yaxis . set_major_formatter (PercentFormatter(1, decimals= 0 ))
plt. show () 

Pandas 히스토그램은 y축에서 소수점 이하 백분율을 제거합니다.

이제 Y축에 소수 자릿수 없이 백분율이 표시됩니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas 히스토그램에 사용되는 저장소 수를 변경하는 방법
Pandas 히스토그램에서 X축 범위를 변경하는 방법
Pandas에서 그룹별로 히스토그램을 그리는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다