source

Seaborn 막대플롯의 축 레이블

goodcode 2022. 9. 12. 11:37
반응형

Seaborn 막대플롯의 축 레이블

다음 코드를 가진 Seaborn 바플롯에 내 라벨을 사용하려고 합니다.

import pandas as pd
import seaborn as sns

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
fig.set_axis_labels('Colors', 'Values')

여기에 이미지 설명 입력

다만, 다음과 같은 에러가 표시됩니다.

AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'

왜 그러고 있어?

Seaborn의 막대 그림은 그림이 아닌 축-객체를 반환합니다.즉, 다음 작업을 수행할 수 있습니다.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

피할 수 있다AttributeError에 의해 야기된set_axis_labels()를 사용하여 메서드를 지정합니다.

matplotlib.pyplot.xlabel 는 x축 라벨을 설정하고 는 현재 축의 y축 라벨을 설정합니다.

솔루션 코드:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

출력 수치:

여기에 이미지 설명 입력

다음과 같이 제목 매개 변수를 추가하여 차트의 제목을 설정할 수도 있습니다.

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

또 다른 방법은 해저 플롯 오브젝트 내에서 직접 메서드에 액세스하는 것입니다.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')

ax.set_xlabel("Colors")
ax.set_ylabel("Values")

ax.set_yticklabels(['Red', 'Green', 'Blue'])
ax.set_title("Colors vs Values") 

작성:

여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/31632637/label-axes-on-seaborn-barplot

반응형