programing tip

y 축을 백분율로 서식 지정

itbloger 2020. 9. 23. 07:22
반응형

y 축을 백분율로 서식 지정


다음과 같은 팬더로 만든 기존 플롯이 있습니다.

df['myvar'].plot(kind='bar')

y 축은 부동 소수점 형식이며 y 축을 백분율로 변경하고 싶습니다. 내가 찾은 모든 솔루션은 ax.xyz 구문 을 사용하며 플롯을 생성하는 위의 줄 아래에만 코드를 배치 할 수 있습니다 (위의 줄 에 ax = ax를 추가 할 수 없음).

위의 선을 변경하지 않고 어떻게 y 축을 백분율로 포맷 할 수 있습니까?

다음은 내가 찾은 해결책 이지만 플롯을 재정의해야합니다 .

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mtick

data = [8,12,15,17,18,18.5]
perc = np.linspace(0,100,len(data))

fig = plt.figure(1, (7,4))
ax = fig.add_subplot(1,1,1)

ax.plot(perc, data)

fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)

plt.show()

위의 솔루션에 연결 : Pyplot : x 축에 백분율 사용


pandas 데이터 프레임 플롯이 자동으로 반환되며 ax원하는대로 축을 조작 할 수 있습니다.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100,5))

# you get ax from here
ax = df.plot()
type(ax)  # matplotlib.axes._subplots.AxesSubplot

# manipulate
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])

여기에 이미지 설명 입력


Jianxun's solution did the job for me but broke the y value indicator at the bottom left of the window.

I ended up using FuncFormatterinstead (and also stripped the uneccessary trailing zeroes as suggested here):

import pandas as pd
import numpy as np
from matplotlib.ticker import FuncFormatter

df = pd.DataFrame(np.random.randn(100,5))

ax = df.plot()
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y))) 

Generally speaking I'd recommend using FuncFormatter for label formatting: it's reliable, and versatile.

여기에 이미지 설명 입력


This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.


For those who are looking for the quick one-liner:

plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()]) 

Or if you are using Latex as the axis text formatter, you have to add one backslash '\'

plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()]) 

I propose an alternative method using seaborn

Working code:

import pandas as pd
import seaborn as sns
data=np.random.rand(10,2)*100
df = pd.DataFrame(data, columns=['A', 'B'])
ax= sns.lineplot(data=df, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='title')
#changing ylables ticks
y_value=['{:,.2f}'.format(x) + '%' for x in ax.get_yticks()]
ax.set_yticklabels(y_value)

여기에 이미지 설명 입력

참고 URL : https://stackoverflow.com/questions/31357611/format-y-axis-as-percent

반응형