LMS
Data Visualisation
plt.subplots()
로 ax를 여러 개 만들고 그냥 plt.xlabel()
하면 어떻게 될까...?
-> 했더니 제일 마지막 ax에 붙는다.
배운 개념 1)
: Pandas의 plot을 사용하면서, matplotlib에서 정의한 subplot 공간 ax를 사용할 수 있다.
plt.plot()
: fig 생성, ax 생성을 거치지 않고 바로 plot을 만들게 해준다.
: 그러면 가장 최근의 figure 객체와 그 subplot에 그린다.
: 만약 subplot이 없으면 하나 생성
그래프 그리는 과정 정리!
1) fig(도화지) 생성 -
fig = plt.figure()
2) ax(축) 생성 -ax = fig.add_subplot(default=(1,1,1))
3) ax에 그래프 메소드 사용 -ax.bar(x, y)
4)plt.xlabel()
,plt.title()
등으로 요소 넣어주기
5)plt.savefig()
으로 이미지 저장*근데 보통 fig, ax 를
plt.subplots()
를 통해동시에 만드는 것 같다.
(이미지 출처 : AIFFEL 노드 11)
plt.bar()
, sns.barplot()
plt.violinplot()
,sns.violinplot()
sns.catplot()
(plt 없음)plt.scatter()
,sns.scatterplot()
plt.plot()
,sns.lineplot()
plt.hist()
,sns.histplot()
sns.heatmap()
df.pivot(index='', columns='', values='')
풀잎스쿨
1) class 기반클래스명:
2) class 상속클래스명(기반클래스명):
issubclass(섭클래스명, 상위클래스명) >>> True 반환하는
함수 쓰기__init__
을 사용하려면 super().__init__()
을 자식 클래스 함수 정의 때 넣어줘서 호출하기class Person:
def __init__(self): # 상위클래스의 초기화 함수 정의
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person):
def __init__(self): # 하위 클래스의 초기화 함수 정의. 이 때 아마 override 되는 듯
print('Student __init__')
super().__init__() # super()로 기반 클래스의 __init__ 메서드 호출
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello)
>>>
Student __init__
Person __init__
파이썬 코딩 도장
안녕하세요.
__init__
함수가 없다면 상위클래스 __init__
을 자동으로 호출해서 attribute error 안 남class Person:
def __init__(self):
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person):
pass # 하위클래스에는 그냥 아무 것도 없지만
james = Student() # 여기서 상위클래스 __init__ 호출
print(james.hello)
super()
에 대한 나의 실험class Person:
def __init__(self):
print("Person __init__ called")
self.hello = 'Person Hi'
class Student(Person):
def __init__(self):
super().__init__()
print("Student __init__ called")
self.study = 'Student study'
self.clean = 'Student clean'
class UniversityStudent(Student):
def __init__(self):
super().__init__()
print('Uni student __init__ called')
self.dissertation = 'Uni student dissertation'
self.clean = 'Uni student clean'
DJ = UniversityStudent()
print('uni att:', DJ.clean)
print('person att:', DJ.hello)
print('student att:',DJ.study)
>>>
Person __init__ called
Student __init__ called
Uni student __init__ called
uni att: Uni student clean
person att: Person Hi
student att: Student study
super()
의 기능super(derived class, self).baseclass의method명
super(Student, self).__init__
를 넣으면 Student 클래스(부모)의 상위인 Person(조부모) 클래스의 __init__
만 호출클래스명.mro()
>>> [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
같은 식으로 순서가 뜸object
는 모든 클래스의 조상...class 클래스명:
할 때 사실 class 클래스명(object):
로 보면 됨@
로: 모든 건 다 이유가 있다...
# df['tip']을 df['sex'] 기준으로 나타내고 싶음
# (1)matplotlib + pandas를 이용한 복잡한 방법
# plt.bar()로 그냥 한 번 해봄(어케 나오나...)
plt.bar(x=df['sex'], height=df['tip'])
>>> 이러면 평균이 'sex'별 평균이 아니었음
# groupby로 평균을 구해줘서 해봄
grouped = df['tip'].groupby(df['sex'])
sex = dict(grouped.mean())
x = list(sex.keys())
y = list(sex.values())
plt.bar(x=x, height=y)
>>> 이러면 평균으로 잘 나옴
# 왜 그런가 봤더니
# plt.bar(x=df['sex'], height=df['tip']) 이렇게 그냥 하면 결국
# grouped.max()를 갖고 그래프를 그림
# 근데 seaborn은
sns.barplot(data=df, x='sex', y='tip')
>>> 이렇게 하니까 'sex'별 평균이었음
>>> 그럼 왜 그럴까 찾아보니
>>> 원래부터 sns.barplot의 리턴값은 아래의 설명임
>>> Show point estimates and confidence intervals as rectangular bars.