본문 바로가기
Python_Wiki/Python_Library

matplotlib/seaborn: bar chart 막대 그래프

by yj-data 2025. 6. 5.

plt.bar

plt.figure(figsize=(10,5))
plt.plot(x=df['col_name'], y=df['col_name2'])
plt.xlabel('col_name')
plt.ylabel('col_name2')
plt.xticks([2005,2010,2015,2020])
plt.ylim(7,10)
plt.savefig('figname.png', dpi=600)

 

sns.barplot(data=df, x='열이름', y='열이름')

#example
df = sns.load_dataset('penguins')

plt.figure(figsize=(10,5))
sns.barplot(data=df, x='species', y='body_mass_g', hue="sex")
plt.title('body mass per species')
plt.xlabel('per species')
plt.ylabel('body mass')
plt.xticks(rotation=30)
plt.legend(loc='upper left')

plt.show()

 

 

sns.countplot()

  • attributes
sns.countplot(
  data=df,
  x='column_name',
  hue='column_name',
  palette=['r','darkred']
)

 

 

example: step by step

#make up the data
dict_data1 = {
    'a':[1,2,1,1,1,1,1,2,2,1,1,1,2,2], 
    'b':[2021,2022,2024,2023,2022,2023,2024,2023,2024,2024,2021,2024,2023,2024]
}
df1 = pd.DataFrame(dict_data1)
df1

 

b를 기준으로 a의 각 값의 개수 구해보기

pie_color = ['r', 'darkred','purple','yellow'] #piechart만들때 만들어둔 색깔군

plt.figure(figsize=(15, 5))

sns.countplot(data=df1, x='b', hue='a',palette=[pie_color[1], pie_color[0]])


plt.suptitle('The Title', fontfamily='monospace', fontsize=15, fontweight='bold')
plt.title('The Second Title', fontfamily='sans-serif', fontsize=12)
#five "generic font family names" (serif, monospace, fantasy, cursive, and sans-serif)

plt.show()

 

 

값이 맞게 나왔는지 가볍게 확인해 보기

df1[['b', 'a']].value_counts()

or

df1.groupby('b')['a'].value_counts().unstack()
# .unstack( ) : 인덱스를 컬럼으로 바꾸는 역할(wide 포맷) 
# .stack( ) : 컬럼을 인덱스로 바꾸는 역할