kaggle :ScatterLine (Q11)

kaggle dictation (05)




plotly.graph_objects as go: 를 이용한 Scatter + line G

산점도

  • bivariate”이변수” 값을 시각화 하는 기본적인 그래프.
    • correlation: Positive, Negative, non
  • 두 개의 변수 각각의 분포과 변수간의 관계를 확인 할 수 있다.

ref.

0. data set

https://www.kaggle.com/miguelfzzz/the-typical-kaggle-data-scientist-in-2021



Subject : 가장 많이 이용하는 computer platform(hardware)

1. data 읽어오기 + data Frame 만들어 주기

1
2
3
4
5
6
7
8
9
10
11
platform = (
df['Q11']
.value_counts()
.to_frame()
.reset_index()
.rename(columns={'index':'Platform', 'Q11':'Count'})
.sort_values(by=['Count'], ascending=False)
.replace(['A deep learning workstation (NVIDIA GTX, LambdaLabs, etc)',
'A cloud computing platform (AWS, Azure, GCP, hosted notebooks, etc)'],
['A deep learning workstation', 'A cloud computing platform'])
)

ide를 dataframe화 완료.

Q11의 column이름 까지 재설정 완료.

Q11



2.표 설정.
1
2
3
4
5
6
7
8
9
10
11
ide = (
ide
.count()
.to_frame()
.reset_index()
.rename(columns={'index':'IDE', 0:'Count'})
.sort_values(by=['Count'], ascending=False)
)


ide['percent'] = ((ide['Count'] / len(df))*100).round(2).astype(str) + '%'


3. percent 추가

1
platform['percent'] = ((platform['Count'] / platform['Count'].sum())*100).round(2).astype(str) + '%'

Q11_percent



3. 색 지정

1
2
3
4
colors = ['#033351',] * 6
colors[5] = '#5abbf9'
colors[4] = '#0779c3'
colors[3] = '#0779c3'


4. 표 재 설정

1
2
3
4
5
platform = (platform
.sort_values(by = ['Count'])
.iloc[0:15]
.reset_index())
platform

platformRe

  1. .sort_values(by = [‘Count’]) : [Count]로 정렬,
  2. .iloc[0:15] platform의 column 선택: 0~15까지 data 가져오기
  3. .reset_index() : data와 상관 없는 새 index 가져오기


5.plotly.graph_objects.Scatter()

본격적으로 Scatter G 만들기.

## 산점도 점 찍기
1
2
3
4
5
6
7
8

fig = go.Figure(go.Scatter(x = platform['Count'],
y = platform["Platform"],
text = platform['percent'],
mode = 'markers',
marker_color =colors,
marker_size = 12))
fig

Q11_graph


  1. x = platform[‘Count’], y = platform[“Platform”],
    1. x축, y축 설정
  2. text = platform[‘percent’],
    1. text를 넣는다고 하는데 안보이네
  3. mode = ‘markers’,
    1. Text, lines+markers, makers, line 이 가능 한거 같다.
    2. Scatter.mod
  4. marker_color =colors, marker_size = 12)
    1. 산점도 안에 있는 점의 색과 크기



## 산점도에 for문을 이용하여 line 연결하기 
1
2
3
4
5
6
for i in range(0, len(platform)):
fig.add_shape(type='line',
x0 = 0, y0 = i,
x1 = platform["Count"][i],
y1 = i,
line=dict(color=colors[i], width = 4))

Q11_Scatter+line

for i in range(0~platform의 길이만큼)

fig. add_shape()

type = ‘line’
- line모양의 grape shape add

x0 = 0, y0 = i,
- 초기값

x1 = platform[“Count”][i],
x축 Index
y1 = i,
y축 Index, 마지막 값

line=dict(color=colors[i], width = 4)

line의 세부 설정, 색과 두께



  • flatform은 .iloc[0:15] 로 뽑아진 list 형식
    따라서 platform[“Count”][i]값을 뽑아 낼 수 있다.




6. update_traces()

1
2
3
fig.update_traces(hovertemplate='<b>Platform</b>: %{y}<br><extra></extra>'+
'<b>Count</b>: %{x}<br>'+
'<b>Proportion</b>: %{text}')


7. Design

1
2
3
4
5
6
7
8
9
10
11
12
13
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='#9f9f9f', ticklabelmode='period')
fig.update_yaxes(showgrid=False)

fig.update_layout(showlegend=False,
plot_bgcolor='#F7F7F7',
margin=dict(pad=20),
paper_bgcolor='#F7F7F7',
yaxis_title=None,
xaxis_title=None,
title_text="Most Commonly Used <b>Computing Platforms</b>",
title_x=0.5,
font=dict(family="Hiragino Kaku Gothic Pro, sans-serif", size=17, color='#000000'),
title_font_size=35)

Q11_layout



8. Annotation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fig.add_annotation(dict(font=dict(size=14),
x=0.98,
y=-0.22,
showarrow=False,
text="@miguelfzzz",
xanchor='left',
xref="paper",
yref="paper"))

fig.add_annotation(dict(font=dict(size=12),
x=0.04,
y=-0.22,
showarrow=False,
text="Source: 2021 Kaggle Machine Learning & Data Science Survey",
xanchor='left',
xref="paper",
yref="paper"))

fig.show()

Q11_final



kaggle :HorizontalBar (Q9)

kaggle dictation (04)




plotly.graph_objects as go: 를 이용한 bar graph

HorizontalBar plot /가로 막대 차트

0. data set

https://www.kaggle.com/miguelfzzz/the-typical-kaggle-data-scientist-in-2021



Subject : 어떤알고리즘을 선호 하는 지 알아보는 Horizontal bar

1. data 읽어오기

1
2
3
4
5
6
# Features that start with Q7
ide_cols = [col for col in df if col.startswith('Q9')]

ide = df[ide_cols]

print(ide)

print(ide)

list comprehension
for문으로 돌린 data값을 전부 col로 받아와서
그 값을 또 ide_cols에 싣는 한줄로 이루어진 코드.

2. data Frame 만들어 주기

ide를 dataframe화 완료.

1
2
3
ide.columns = ['JupyterLab', 'RStudio', 'Visual Studio', 'VSCode', 
'PyCharm', 'Spyder', 'Notepad++', 'Sublime Text', 'Vim, Emacs, or similar',
'MATLAB', 'Jupyter Notebook', 'None', 'Other']

Q9의 column이름 재 설정.



3.표 설정.
1
2
3
4
5
6
7
8
ide = (
ide
.count()
.to_frame()
.reset_index()
.rename(columns={'index':'IDE', 0:'Count'})
.sort_values(by=['Count'], ascending=False)
)


3. percent 추가

1
ide['percent'] = ((ide['Count'] / len(df))*100).round(2).astype(str) + '%'


4. 색 지정

1
2
3
4
5
6
7
8
9
colors = ['#033351',] * 13
colors[0] = '#5abbf9'
colors[1] = '#5abbf9'
colors[2] = '#0779c3'
colors[3] = '#0779c3'
colors[4] = '#0779c3'
colors[5] = '#0779c3'
colors[6] = '#0779c3'
colors[7] = '#0779c3'


5. bar Graph 만들기

1
2
3
4
5
6
7
fig = go.Figure(go.Bar(
x=ide['Count'],
y=ide['IDE'],
text=ide['percent'],
orientation='h',
marker_color=colors
))


6. update_traces()

1
2
3
4
5
6
fig.update_traces(texttemplate='%{text}', 
textposition='outside',
cliponaxis = False,
hovertemplate='<b>IDE</b>: %{y}<br><extra></extra>'+
'<b>Count</b>: %{x}',
textfont_size=12)


7. Design

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fig.update_xaxes(showgrid=False)
fig.update_yaxes(showgrid=False)

fig.update_layout(showlegend=False,
plot_bgcolor='#F7F7F7',
margin=dict(pad=20),
paper_bgcolor='#F7F7F7',
xaxis={'showticklabels': False},
yaxis_title=None,
height = 600,
xaxis_title=None,
yaxis={'categoryorder':'total ascending'},
title_text="Most Commonly Used <b>IDE's</b>",
title_x=0.5,
font=dict(family="Hiragino Kaku Gothic Pro, sans-serif", size=15, color='#000000'),
title_font_size=35)


8. Annotation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fig.add_annotation(dict(font=dict(size=14),
x=0.98,
y=-0.17,
showarrow=False,
text="@miguelfzzz",
xanchor='left',
xref="paper",
yref="paper"))

fig.add_annotation(dict(font=dict(size=12),
x=0,
y=-0.17,
showarrow=False,
text="Source: 2021 Kaggle Machine Learning & Data Science Survey",
xanchor='left',
xref="paper",
yref="paper"))


fig.show()


kaggle :HorizontalBar (Q17)

kaggle dictation (03)




plotly.graph_objects as go: 를 이용한 bar graph

HorizontalBar plot /가로 막대 차트

0. data set

https://www.kaggle.com/miguelfzzz/the-typical-kaggle-data-scientist-in-2021



Subject : 어떤알고리즘을 선호 하는 지 알아보는 Horizontal bar

1. data 읽어오기

algorithms_cols에 data frame을 먼저 만들고 시작.
잘 모르겠지만 아마도 Q17이 붙은 data를 선택 하기 위한 code

algorithms_cols = [col for col in df if col.startswith(‘Q17’)]

col 1부터 df 끝까지

Q17로 시작하는지 확인하여 true일때만 데이터 가져오기

ref.

How to select dataframe columns that start with *** using pandas in python ?

1
2
algorithms_cols = [col for col in df if col.startswith('Q17')]



2. data Frame 만들어 주기

algorithms 에 data frame을 씌워서 표를 만들고, 이름을 다음과같이 바꿔줌.

1
2
3
4
5
6
7
8

algorithms = df[algorithms_cols]

algorithms.columns = ['Linear or Logistic Regression', 'Decision Trees or Random Forests',
'Gradient Boosting Machines', 'Bayesian Approaches', 'Evolutionary Approaches',
'Dense Neural Networks', 'Convolutional Neural Networks', 'Generative Adversarial Networks',
'Recurrent Neural Networks', 'Transformer Networks', 'None', 'Other']


algorithms


3.표 설정.
1
2
3
4
5
6
7
8
algorithms = (
algorithms
.count()
.to_frame()
.reset_index()
.rename(columns={'index':'Algorithms', 0:'Count'})
.sort_values(by=['Count'], ascending=False)
)


  1. .count() :coulumn 수 세기
  2. .to_frame() : frame 생성
  3. .reset_index() : 원본과 상관없는 Index 생성
  4. .rename()
    1. columns의 이름을 지정 : ‘index’:’Algorithms’, 0:’Count’
  5. .sort_values()
    1. by=[‘Count’], ascending=False
    2. Count 기준으로 내림차순으로 정렬


3. percent 추가

1
2
algorithms['percent'] = ((algorithms['Count'] / len(df))*100).round(2).astype(str) + '%'



표에 ‘percent’를 추가
algorithms의 count에 df의 length로 나누고 *100을 하는 전형적인 % 나타내기

값자체에 %를 입력하여 나중에 %를 추가 입력하지 않아도 됨

소숫점 자리 2까지 반영(반올림).
type 자체를 String으로 하여 추가 계산은 불가능.



4. 색 지정

1
2
3
4
5
6
7
8
colors = ['#033351',] * 12
colors[0] = '#5abbf9'
colors[1] = '#5abbf9'
colors[2] = '#066eb0'
colors[3] = '#066eb0'
colors[4] = '#044a77'
colors[5] = '#044a77'
colors[6] = '#044a77'

colors


색 깊이는 12단계, 0~6까지는 정해주고 나머지 5개는 #033351을 default로 한 것을 알 수 있다.


5. bar Graph 만들기

1
2
3
4
5
6
7
fig = go.Figure(go.Bar(
x=algorithms['Count'],
y=algorithms['Algorithms'],
text=algorithms['percent'],
orientation='h',
marker_color=colors
))

horizontal과 vertical Graph의 차이는 x, y axis를 바꾸어 주는 것과

orientation=’h’ 을 넣어 주는 것의 차이.


<orientation 없음>

orientationH


<orientation H 있음>

orientationH_


6. update_traces()

traces() 수정 : Trace에 대한 설정

1
2
3
4
5
6
fig.update_traces(texttemplate='%{text}', 
textposition='outside',
cliponaxis = False,
hovertemplate='<b>Algorithm</b>: %{y}<br><extra></extra>'+
'<b>Count</b>: %{x}',
textfont_size=12)
  1. texttemplate : text type
  2. textposition : ‘outside’ _ 설정 해 주지 않은 경우 칸에 따라 적당히 들어감.
  3. cliponaxis = False : text가 칸이 작아서 짤리는 경우를 막아주는 기능 (off)
  4. hovertemplate :
    1. 마우스 On하면 (커서를 위에 대면) 나오는 Hovert에대한 설정.
  5. textfont_size : 폰트 size



7. Design

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

fig.update_xaxes(showgrid=False)
fig.update_yaxes(showgrid=False)

fig.update_layout(showlegend=False,
plot_bgcolor='#F7F7F7',
margin=dict(pad=20),
paper_bgcolor='#F7F7F7',
xaxis={'showticklabels': False},
yaxis_title=None,
height = 600,
xaxis_title=None,
yaxis={'categoryorder':'total ascending'},
title_text="Most Commonly Used <b>Algorithms</b>",
title_x=0.5,
font=dict(family="Hiragino Kaku Gothic Pro, sans-serif", size=15, color='#000000'),
title_font_size=35)
  1. Grid Delete

grid delete


  1. update_layout
    1. showlegend=False,
    2. plot_bgcolor=’#F7F7F7’
    3. margin=dict(pad=20),
    4. paper_bgcolor=’#F7F7F7’,
    5. xaxis={‘showticklabels’: False},
      1. x 축 labels을 삭제.
    6. yaxis_title=None,
    7. xaxis_title=None, yaxis={‘categoryorder’:’total ascending’},
      1. y 축 title을 categoryorder
      2. img.png
      3. Automatically Sorting Categories by Name or Total Value
      4. layout-xaxis-categoryorder
    8. title_text=”Most Commonly Used Algorithms“,
    9. title_x=0.5,
    10. font=dict(family=”Hiragino Kaku Gothic Pro, sans-serif”, size=15, color=’#000000’),
             title_font_size=35)
      

이미 앞서서 충분히 설명 했기 때문에 본 posting에서 설명되지 않은 부분은

basic bar Graph 에서 확인

8. Annotation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fig.add_annotation(dict(font=dict(size=14),
x=0.98,
y=-0.17,
showarrow=False,
text="@miguelfzzz",
xanchor='left',
xref="paper",
yref="paper"))

fig.add_annotation(dict(font=dict(size=12),
x=0,
y=-0.17,
showarrow=False,
text="Source: 2021 Kaggle Machine Learning & Data Science Survey",
xanchor='left',
xref="paper",
yref="paper"))


fig.show()