판다스
판다스 입문 4장 데이터 시각화- 그래프 그리기
막막한
2023. 3. 4. 18:21
앤스콤 데이터 집합 불러오기¶
In [2]:
#seaborn 라이브러리 load_dataset메서드 문자열 anscombe 전달= 앤스콤 데이터 집합 불러올 수 있음
import seaborn as sns
anscombe=sns.load_dataset("anscombe")
anscombe
Out[2]:
dataset | x | y | |
---|---|---|---|
0 | I | 10.0 | 8.04 |
1 | I | 8.0 | 6.95 |
2 | I | 13.0 | 7.58 |
3 | I | 9.0 | 8.81 |
4 | I | 11.0 | 8.33 |
5 | I | 14.0 | 9.96 |
6 | I | 6.0 | 7.24 |
7 | I | 4.0 | 4.26 |
8 | I | 12.0 | 10.84 |
9 | I | 7.0 | 4.82 |
10 | I | 5.0 | 5.68 |
11 | II | 10.0 | 9.14 |
12 | II | 8.0 | 8.14 |
13 | II | 13.0 | 8.74 |
14 | II | 9.0 | 8.77 |
15 | II | 11.0 | 9.26 |
16 | II | 14.0 | 8.10 |
17 | II | 6.0 | 6.13 |
18 | II | 4.0 | 3.10 |
19 | II | 12.0 | 9.13 |
20 | II | 7.0 | 7.26 |
21 | II | 5.0 | 4.74 |
22 | III | 10.0 | 7.46 |
23 | III | 8.0 | 6.77 |
24 | III | 13.0 | 12.74 |
25 | III | 9.0 | 7.11 |
26 | III | 11.0 | 7.81 |
27 | III | 14.0 | 8.84 |
28 | III | 6.0 | 6.08 |
29 | III | 4.0 | 5.39 |
30 | III | 12.0 | 8.15 |
31 | III | 7.0 | 6.42 |
32 | III | 5.0 | 5.73 |
33 | IV | 8.0 | 6.58 |
34 | IV | 8.0 | 5.76 |
35 | IV | 8.0 | 7.71 |
36 | IV | 8.0 | 8.84 |
37 | IV | 8.0 | 8.47 |
38 | IV | 8.0 | 7.04 |
39 | IV | 8.0 | 5.25 |
40 | IV | 19.0 | 12.50 |
41 | IV | 8.0 | 5.56 |
42 | IV | 8.0 | 7.91 |
43 | IV | 8.0 | 6.89 |
In [3]:
type(anscombe)
Out[3]:
pandas.core.frame.DataFrame
matplotlib 라이브러리로 간단한 그래프 그리기¶
In [4]:
# %matplotlib notebook
import matplotlib.pyplot as plt
dataset_1=anscombe[anscombe['dataset']=='I'] #데이터값이 I인 것만 추출/ 첫 번째 데이터 그룹 추출
plt.plot(dataset_1['x'], dataset_1['y'])
Out[4]:
[<matplotlib.lines.Line2D at 0x13fa7c320d0>]
In [5]:
#선말고 점으로 그래프 그리고 싶다면
dataset_1=anscombe[anscombe['dataset']=='I'] #데이터값이 I인 것만 추출/ 첫 번째 데이터 그룹 추출
plt.plot(dataset_1['x'], dataset_1['y'], 'o')
Out[5]:
[<matplotlib.lines.Line2D at 0x13fa7e6bf70>]
한 번에 4개의 그래프 그리기¶
In [6]:
dataset_2=anscombe[anscombe['dataset']=='II']
dataset_3=anscombe[anscombe['dataset']=='III']
dataset_4=anscombe[anscombe['dataset']=='IV']
In [7]:
<Figure size 640x480 with 0 Axes>
In [10]:
fig=plt.figure()
axes1=fig.add_subplot(2,2,1) #add_subplot 첫 번째 인자, 행 크기, 두 번째 인자 그래프 기본 틀의 열 크기 지정 , 세번째 인자 순서
axes2=fig.add_subplot(2,2,2)
axes3=fig.add_subplot(2,2,3)
axes4=fig.add_subplot(2,2,4)
In [11]:
#점으로 그래프 표현
axes1.plot(dataset_1['x'], dataset_1['y'], 'o')
axes2.plot(dataset_2['x'], dataset_2['y'], 'o')
axes3.plot(dataset_3['x'], dataset_3['y'], 'o')
axes4.plot(dataset_4['x'], dataset_4['y'], 'o')
fig #그래프 확인하기 위해 fig 입력
Out[11]:
In [12]:
#그래프 구별하기 위해 그래프 격자에 제목 추가하기
#set_title 메서드 이용
axes1.set_title("dataset_1")
axes2.set_title("dataset_2")
axes3.set_title("dataset_3")
axes4.set_title("dataset_4")
fig
Out[12]:
In [13]:
#기본틀에 제목 추가하기
#suptitle 메서드 이용
fig.suptitle("Anscombe Data")
fig
Out[13]:
In [14]:
#레이아웃 조절하기
fig.tight_layout()
fig
Out[14]:
기초 그래프 그리기 - 히스토그램, 산점도, 박스 그래프¶
In [15]:
#팁 정보 데이터 불러오기
tips=sns.load_dataset("tips")
print(tips.head())
print(type(tips))
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
<class 'pandas.core.frame.DataFrame'>
In [16]:
fig= plt.figure()
axes1= fig.add_subplot(1,1,1)
In [17]:
#hist메서드에 total_bill 열 전달해 히스토그램 만들어짐
#x축 간격은 bins 인잣값으로 조정 / bins 인잣갑 10으로 지정하면, x축 간격 10
axes1.hist(tips['total_bill'], bins=10)
axes1.set_title('Histogram of Total Bill') #그래프 제목
axes1.set_xlabel('Frequency')
axes1.set_ylabel('Total Bill')
fig
Out[17]:
In [19]:
#산점도 그래프 scatter plot
scatter_plot = plt.figure()
axes1=scatter_plot.add_subplot(1,1,1)
axes1.scatter(tips['total_bill'], tips['tip'])
axes1.set_title('Scatterplot of Total Bill vs Tip')
axes1.set_xlabel('Total Bill')
axes1.set_ylabel('Tip')
Out[19]:
Text(0, 0.5, 'Tip')
In [21]:
#박스 그래프 x- 이산형 변수 /y- 연속형 변수
# boxplot 메서드 사용
boxplot=plt.figure()
axes1= boxplot.add_subplot(1,1,1)
#tips 데이터프레임에서 성별이 female, male인 데이터에서 tip열 데이터 추출해 리스트에 담아 전달
axes1.boxplot([tips[tips['sex']=='Female']['tip'],
tips[tips['sex']=='Male']['tip']],
labels=['Female', 'Male'])
axes1.set_xlabel('sex')
axes1.set_ylabel('tip')
axes1.set_title('boxplot of tips by sex')
Out[21]:
Text(0.5, 1.0, 'boxplot of tips by sex')
In [22]:
#다변량 산점도 그래프
#여성 0 반환, 남성 1 반환
def recode_sex(sex):
if sex == 'Female':
return 0
else:
return 1
In [23]:
#recode_sex 반환값을 sex_color 열로 새로 생성해 데이터 프레임에 추가
#sex 열에 recode_sex 함수 브로드캐스팅 하기 위해 apply 메서드 사용
tips['sex_color']= tips['sex'].apply(recode_sex)
In [24]:
#테이블당 인원 수 (size) 산점도 그래프에 추가
#scatter 메서드에 s,c 인잣값으로 테이블당 인원 수와 성별의 치환값 전달
scatter_plot = plt.figure()
axes1= scatter_plot.add_subplot(1,1,1)
axes1.scatter(
x=tips['total_bill'],
y=tips['tip'],
s=tips['size']*10, #s 점의 크기
c=tips['sex_color'], #c 점의 색상
alpha=0.5) #alpha 투명도
axes1.set_title('total bill vs tip colored by sex and sized by size')
axes1.set_xlabel('total bill')
axes1.set_ylabel('tip')
Out[24]:
Text(0, 0.5, 'tip')
단변량 그래프 그리기 - 히스토그램¶
In [25]:
import seaborn as sns
tips=sns.load_dataset("tips")
In [27]:
#subplots 메서드로 기본 틀 만들기/ distplot 메서드로 totall_bill 열 데이터 전달해 히스토그램 그리기
ax=plt.subplots()
ax=sns.distplot(tips['total_bill'])
ax.set_title('total bill histogram with density plot')
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
warnings.warn(msg, FutureWarning)
Out[27]:
Text(0.5, 1.0, 'total bill histogram with density plot')
In [28]:
#밀집도 그래프 제외하고 싶다면 kde 인잣값을 false로 설정
ax= plt.subplots()
ax=sns.distplot(tips['total_bill'], kde=False)
ax.set_title('total bill histogram')
ax.set_xlabel('tatal bill')
ax.set_ylabel('frequency')
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
warnings.warn(msg, FutureWarning)
Out[28]:
Text(0, 0.5, 'frequency')
In [29]:
#밀집도 그래프만 나타내려면 hist 인자를 false
ax=plt.subplots()
ax=sns.distplot(tips['total_bill'], hist=False)
ax.set_title('total bill density')
ax.set_xlabel('tatal bill')
ax.set_ylabel('unit probability')
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)
Out[29]:
Text(0, 0.5, 'unit probability')
In [30]:
# 실무 환경에서는 여러 그래프 한 번에 출력
#히스토그램과 밀집도 그리는 distplot 메서드에 rug 인자 추가해 양탄자 그래프 그리지
#양탄자(rug) 그래프는 그래프의 축에 동일한 길이 직선 붙여 데이터 밀집 정도 표현한 그래프
ax=plt.subplots()
ax=sns.distplot(tips['total_bill'], rug=True)
ax.set_xlabel('total bill')
ax.set_ylabel('unit porbability')
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
warnings.warn(msg, FutureWarning)
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2103: FutureWarning: The `axis` variable is no longer used and will be removed. Instead, assign variables directly to `x` or `y`.
warnings.warn(msg, FutureWarning)
Out[30]:
Text(0, 0.5, 'unit porbability')
In [31]:
#count 그래프는 이산값을 나타낸 그래프
#countplot 메서드에 tips 데이터 프레임의 day 열 넣기
ax=plt.subplots()
ax=sns.countplot('day', data=tips)
ax.set_title('count of days')
ax.set_xlabel('day of the week')
ax.set_ylabel('frequency')
C:\Users\82104\anaconda3\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
Out[31]:
Text(0, 0.5, 'frequency')
다양한 종류의 이변량 그래프 그리기¶
In [32]:
# seaborn 산점도 그래프 그리기 / regplot 메서드 사용
#회귀선 제거하려면 fit_reg=False
ax= plt.subplots()
ax=sns.regplot(x='total_bill', y='tip', data=tips)
ax.set_title('scatterplot of total bill and tip')
ax.set_xlabel('total bill')
ax.set_ylabel('tip')
Out[32]:
Text(0, 0.5, 'tip')
In [33]:
#회귀선 삭제
ax= plt.subplots()
ax=sns.regplot(x='total_bill', y='tip', data=tips, fit_reg=False)
ax.set_title('scatterplot of total bill and tip')
ax.set_xlabel('total bill')
ax.set_ylabel('tip')
Out[33]:
Text(0, 0.5, 'tip')
In [34]:
#산점도 그래프와 히스토그래미 한 번에 그려주는 jointplot 메서드 사용
#x y 인자에 원하는 열 이름 지정하고 data 인잣값으로 데이터프레임 지정
joint=sns.jointplot(x='total_bill', y='tip', data=tips)
joint.set_axis_labels(xlabel='total bill', ylabel='tip')
joint.fig.suptitle('joint plot of total bill and tip', fontsize=10, y=1.03)
Out[34]:
Text(0.5, 1.03, 'joint plot of total bill and tip')
In [35]:
#산점도 그래프가 점이 겹쳐 , 구분하기 어렵다 --> 육각 그래프 사용
#kind 인잣값을 hex 로 지정
hexbin = sns.jointplot(x="total_bill", y="tip", data=tips, kind="hex")
hexbin.set_axis_labels(xlabel='total bill', ylabel='tip')
hexbin.fig.suptitle('hexbin joint plot of tatal bill and tip', fontsize=10, y=1.03)
Out[35]:
Text(0.5, 1.03, 'hexbin joint plot of tatal bill and tip')
In [39]:
#이차원 밀집도 그리기 - kdeplot 메서드 사용
# shade 인잣값 true 지정하면 음영효과 줄 수 있다
ax=plt.subplots()
ax=sns.kdeplot(data=tips['total_bill'], data2=tips['tip'], shade=True)
ax.set_title('kernel density plot of tatal bill and tip')
ax.set_xlabel('total bill')
ax.set_ylabel('tip')
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:1681: FutureWarning: Use `x` and `y` rather than `data` `and `data2`
warnings.warn(msg, FutureWarning)
Out[39]:
Text(0, 0.5, 'tip')
In [40]:
#바그래프 그리기 = 지정 변수의 평균 계산
ax=plt.subplots()
ax=sns.barplot(x='time', y='total_bill', data=tips)
ax.set_title('bar plot of average tatal bill for time of day')
ax.set_xlabel('time of day')
ax.set_ylabel('average total bill')
Out[40]:
Text(0, 0.5, 'average total bill')
In [42]:
# 박스 그래프 그리기- 다양한 통계량 한 번에 표현
ax=plt. subplots()
ax=sns.boxplot(x='time', y='total_bill', data=tips)
ax.set_title('boxplot of total bill by time of day')
ax.set_xlabel('time of day')
ax.set_ylabel('total bill')
Out[42]:
Text(0, 0.5, 'total bill')
In [43]:
# 박스그래프는 다양한 통계 수치 확인하기 위해 사용하지만 데이터 분산이 모호하다
# 박스 그래프에 커널 밀도를 추정한 바이올린 그래프 사용해라 --- violinplot 메서드
ax=plt.subplots()
ax=sns.violinplot(x='time', y='total_bill', data=tips)
ax.set_title('violin plot of total bill by time of day')
ax.set_xlabel('time of day')
ax.set_ylabel('total bill')
Out[43]:
Text(0, 0.5, 'total bill')
In [44]:
# 관계 그래프 -- 종합 그래프라 생각 --- pairplot 메서드
fig=sns.pairplot(tips)
In [45]:
# 관계 그래프는 중복된 정보 표현된다
# map_upper 대각선 기준으로 위쪽 그래프
# map_lower 대각선 기준으로 아래 그래프
# map_diag 대각선을 중심으로 그래프 그림
pair_grid = sns.PairGrid(tips)
pair_grid=pair_grid.map_upper(sns.regplot)
pair_grid=pair_grid.map_lower(sns.kdeplot)
pair_grid=pair_grid.map_diag(sns.displot, rug=True)
plt.show()
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2211: UserWarning: `displot` is a figure-level function and does not accept the ax= paramter. You may wish to try histplot.
warnings.warn(msg, UserWarning)
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2211: UserWarning: `displot` is a figure-level function and does not accept the ax= paramter. You may wish to try histplot.
warnings.warn(msg, UserWarning)
C:\Users\82104\anaconda3\lib\site-packages\seaborn\distributions.py:2211: UserWarning: `displot` is a figure-level function and does not accept the ax= paramter. You may wish to try histplot.
warnings.warn(msg, UserWarning)
다변량 그래프 그리기¶
In [46]:
# seaborn 라이브러리로 다변량 -색상 추가
# violinplot 메서드에 hue ㅡ인잣값으로 색상에 사용할 열 이름 추가
ax= plt.subplots()
ax=sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True)
In [51]:
# 산점도, 관계 그래프 색상 추가
scatter=sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex', fit_reg=False)
In [52]:
fig=sns.pairplot(tips, hue='sex')
데이터프레임과 시리즈로 그래프 그리기¶
In [53]:
# hist 메서드 사용== 해당 시리즈의 값 이용해 히스토그램 그릴 수 있다
ax= plt.subplots()
ax=tips['total_bill'].plot.hist()
In [56]:
# 투명도 조절 - hist 메서드의 alpha, bins, ax 인자 사용
fig, ax= plt.subplots()
ax= tips[['total_bill', 'tip'].plot.hist(alpha=0.5, bins=20, ax=ax)
File "C:\Users\Public\Documents\ESTsoft\CreatorTemp\ipykernel_14176\2112071198.py", line 4
ax= tips[['total_bill', 'tip'].plot.hist(alpha=0.5, bins=20, ax=ax)
^
SyntaxError: unexpected EOF while parsing
In [57]:
ax=plt.subplots()
ax=tips['tip'].plot.kde()
알아두면 좋아요¶
In [ ]: