[데이터분석] 서울시 범죄 현황 데이터 시각화

·2023년 4월 1일
0
post-thumbnail

🔎 서울시 범죄 현황 분석


1. 서울시 범죄현황 데이터 시각화

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import rc

plt.rcParams['axes.unicode_minus']=False
get_ipython().run_line_magic('matplotlib','inline')
rc('font',family='Malgun Gothic')

crime_anal_norm.head()
-강도살인강간절도폭력강간검거율강도검거율살인검거율절도검거율폭력검거율인구수CCTV범죄검거
구별
강남구1.0000000.3571431.0000000.9771180.73377380.038760100.000000100.00000053.47086788.13093553498832380.81360784.328112
강동구0.3589740.2857140.3100780.4777990.46388095.00000092.857143100.00000051.42531486.99604746449010100.37928985.255701
강북구0.1282050.5000000.4205430.3328790.50935173.27188980.00000085.71428654.99181789.3448522986228310.37819676.664569
관악구0.3076920.4285710.6240310.5728680.59314381.98757883.333333100.00000044.55539783.67851650075021090.50526178.710965
광진구0.2820510.2857140.5406980.7180600.43857783.87096854.545455100.00000040.09863484.0719063510738780.45302072.517393
# pairplot 강도, 살인, 폭력에 대한 상관관계 확인

sns.pairplot(data=crime_anal_norm, vars=['살인','강도','폭력'],kind='reg',height=3 )

# '인구수', 'cctv' 와 '살인', '강도' 상관관계 
def drawGraph():
    sns.pairplot(
        data=crime_anal_norm,
        x_vars=['인구수','CCTV'],
        y_vars=['살인','강도'],
        kind='reg',
        height=4
    )
    plt.show()
    
drawGraph()

#'인구수','cctv' 와 '실인검거율', '폭력검거율의 상관관계'
def drawGraph():
    sns.pairplot(
        data=crime_anal_norm,
        x_vars=['인구수','CCTV'],
        y_vars=['살인검거율','강도검거율'],
        kind='reg',
        height=4
    )
    plt.show()
    
drawGraph()

#검거율 heatmap
# '검거'라는 컬럼을 기준으로 정렬
# 위에서 삭제한 감가 컬럼 추가 

def drawGraph():
    
    
    #데이터 프레임 생성 
    target_col=['강간검거율','강도검거율','살인검거율','절도검거율','폭력검거율','검거']
    crime_anal_norm_sort=crime_anal_norm.sort_values(by='검거',ascending=False)
    
    #그래프 설정 
    plt.figure(figsize=(10,10))
    sns.heatmap(
        data=crime_anal_norm_sort[target_col],
        annot=True, #데이터값 표시
        fmt='f', #실수형
        linewidths=1, #간격설정
        cmap='RdPu'
        
    )
    plt.title('범죄 검거 비율(정규화된 검거의 합으로 정렬)')
    plt.show()
    
drawGraph()

# 범죄발생 건수 heatmap
# 범죄 컬럼 기준 정렬

def drawGraph():
    #데이터 설정 
    target_col=['살인','강도','강간','절도','폭력','범죄']
    crime_anal_norm_sort=crime_anal_norm[target_col].sort_values(by='범죄',ascending=False)
    #그래프 그리기 
    plt.figure(figsize=(10,10))
    sns.heatmap(
         data=crime_anal_norm_sort[target_col],
        annot=True, #데이터값 표시
        fmt='f', #실수형
        linewidths=1, #간격설정
        cmap='RdPu'
    )
    plt.title('범죄 발생 비율(정규화된 범죄의 합으로 정렬)')
    plt.show()

drawGraph()


### folium
#folium 설치 
!pip install folium
import folium
import pandas as pd
import json

folium.Map()

Examples


>>> m = folium.Map(location=[45.523, -122.675], width=750, height=500)
>>> m = folium.Map(location=[45.523, -122.675], tiles="cartodb positron")
>>> m = folium.Map(
...     location=[45.523, -122.675],
...     zoom_start=2,
...     tiles="https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=mytoken",
...     attr="Mapbox attribution",
... )
folium.Map(location=[45.523, -122.675], width=750, height=500)

m=folium.Map(location=[37.5094853,127.1020849], #석촌호수
            zoom_start=16) #0 - 18

m

tiles option

to Folium. Pass any of the following to the "tiles" keyword:

  • "OpenStreetMap"
  • "Mapbox Bright" (Limited levels of zoom for free tiles)
  • "Mapbox Control Room" (Limited levels of zoom for free tiles)
  • "Stamen" (Terrain, Toner, and Watercolor)
  • "Cloudmade" (Must pass API key)
  • "Mapbox" (Must pass API key)
  • "CartoDB" (positron and dark_matter)
m=folium.Map(location=[37.5094853,127.1020849],
            zoom_start=16,#0 - 18
            tiles='Stamen Watercolor' #지도스타일
            ) 

m

m=folium.Map(location=[37.5094853,127.1020849],
            zoom_start=16,#0 - 18
            tiles='CartoDB positron' #지도스타일
            ) 

m

folium.Maker()

  • 지도에 표시 생성

        Init signature:
        folium.Marker(
            location=None,
            popup=None,
            tooltip=None,
            icon=None,
            draggable=False,
            **kwargs,
        )
        Docstring:     
        Create a simple stock Leaflet marker on the map, with optional
        popup text or Vincent visualization.
    
        Parameters
        ----------
        location: tuple or list
            Latitude and Longitude of Marker (Northing, Easting)
        popup: string or folium.Popup, default None
            Label for the Marker; either an escaped HTML string to initialize
            folium.Popup or a folium.Popup instance.
        tooltip: str or folium.Tooltip, default None
            Display a text when hovering over the object.
        icon: Icon plugin
            the Icon plugin to use to render the marker.
        draggable: bool, default False
            Set to True to be able to drag the marker around the map.
            
            Examples
        --------
        >>> Marker(location=[45.5, -122.3], popup="Portland, OR")
        >>> Marker(location=[45.5, -122.3], popup=Popup("Portland, OR"))
        # If the popup label has characters that need to be escaped in HTML
        >>> Marker(
        ...     location=[45.5, -122.3],
        ...     popup=Popup("Mom & Pop Arrow Shop >>", parse_html=True),

    ... )

m=folium.Map(location=[37.5094853,127.1020849], #석촌호수
            zoom_start=15,#0 - 18
            tiles="OpenStreetMap"
            ) 

folium.Marker(location=[37.5088511,127.0995137],
             popup=folium.Popup("<center>롯데월드 매직아일랜드</center>", min_width=150, max_width=150), #html 문법 가능
             tooltip='<i>Magic Island</i>'
             ).add_to(m) 


m             


folium.Marker(location=[37.5088511,127.0995137],
             popup=folium.Popup("<center><a href= 'https://goo.gl/maps/QzbYbRKfAnUv136K8' target=_'blink'>매직아일랜드</a></center>",
                                min_width=150,
                               max_width=150), #html 문법 가능
             tooltip='<i>매직아일랜드 info</i>'
             ).add_to(m) 


m  

folium.Icon()

Init signature:
folium.Icon(
    color='blue',
    icon_color='white',
    icon='info-sign',
    angle=0,
    prefix='glyphicon',
    **kwargs,
)
Docstring:     
Creates an Icon object that will be rendered
using Leaflet.awesome-markers.

Parameters
----------
color : str, default 'blue'
    The color of the marker. You can use:

        ['red', 'blue', 'green', 'purple', 'orange', 'darkred',
         'lightred', 'beige', 'darkblue', 'darkgreen', 'cadetblue',
         'darkpurple', 'white', 'pink', 'lightblue', 'lightgreen',
         'gray', 'black', 'lightgray']

icon_color : str, default 'white'
    The color of the drawing on the marker. You can use colors above,
    or an html color code.
icon : str, default 'info-sign'
    The name of the marker sign.
    See Font-Awesome website to choose yours.
    Warning : depending on the icon you choose you may need to adapt
    the `prefix` as well.
angle : int, default 0
    The icon will be rotated by this amount of degrees.
prefix : str, default 'glyphicon'
    The prefix states the source of the icon. 'fa' for font-awesome or
    'glyphicon' for bootstrap 3.
    
folium.Marker(location=[37.5088511,127.0995137],
             popup=folium.Popup("<center><a href= 'https://goo.gl/maps/QzbYbRKfAnUv136K8' target=_'blink'>매직아일랜드</a></center>",
                                min_width=150,
                               max_width=150), #html 문법 가능
             tooltip='<i>매직아일랜드 info</i>',
            icon=folium.Icon(
                color='lightblue',
                icon_color='black',
                icon='cloud'
            
            )
             ).add_to(m) 


m             

# icon custom 
# icon - list >>> https://getbootstrap.com/docs/3.3/components/
custom_icon=folium.Icon(
    color='blue',
    icon_color='yellow',
    icon='star'

)
custom_popup=folium.Popup(
    "<center><a href= 'https://goo.gl/maps/QzbYbRKfAnUv136K8' target=_'blink'>매직아일랜드</a></center>",
                                min_width=150,
                               max_width=150
) 

folium.Marker(location=[37.5088511,127.0995137],
             popup=custom_popup,
             tooltip='<i>매직아일랜드 info</i>',
             icon=custom_icon
).add_to(m) 


m       

# icon custom , frefix = 'fa'
# icon - list >>> https://fontawesome.com/search?m=free&o=r
custom_icon=folium.Icon(
    color='blue',
    icon_color='white',
    icon='ghost',
    prefix='fa'

)
custom_popup=folium.Popup(
    "<center><a href= 'https://goo.gl/maps/QzbYbRKfAnUv136K8' target=_'blink'>매직아일랜드</a></center>",
                                min_width=150,
                               max_width=150
) 

folium.Marker(location=[37.5088511,127.0995137],
             popup=custom_popup,
             tooltip='<i>매직아일랜드 info</i>',
             icon=custom_icon
).add_to(m) 


m 

folium.ClickForMarker()

- 지도위에 마우스를 클릭했을 때 마커 생성 
m=folium.Map(location=[37.5094853,127.1020849], #석촌호수
            zoom_start=15,#0 - 18
            tiles="OpenStreetMap"
            ) 

m.add_child(folium.ClickForMarker(
    popup='ClickForMarker'
))

m
       

folium.LatLngPopup()

  • 지도를 클릭했을 때 위도 걍도 정보를 반환한다

folium.Circle(), folium.CircleMarker()

Init signature: folium.Circle(location=None, radius=50, popup=None, tooltip=None, **kwargs)
Docstring:     
Class for drawing circle overlays on a map.

It's an approximation and starts to diverge from a real circle closer to
the poles (due to projection distortion).

See :func:`folium.vector_layers.path_options` for the `Path` options.

Parameters
----------
location: tuple[float, float]
    Latitude and Longitude pair (Northing, Easting)
popup: string or folium.Popup, default None
    Input text or visualization for object displayed when clicking.
tooltip: str or folium.Tooltip, default None
    Display a text when hovering over the object.
radius: float
    Radius of the circle, in meters.
    
m=folium.Map(location=[37.5749373,126.9786355], #종로구
         zoom_start=14,#0 - 18
            tiles="OpenStreetMap"
            ) 

#circle
folium.Circle(
     location=[37.565643683342, 126.95524147826], #경복궁
     radius=100,
     fill=True,
     color='#ffd324',
     fill_color='#ffd324',
     popup='경복궁',
     toltip='Circle'

).add_to(m)

#circleMarker
folium.CircleMarker(
     location=[37.580888310281, 126.98838803559 ], #창덕궁
     radius=30,
     fill=True,
     color='#ff085a',
     fill_color='#ff085a',
     popup='창덕궁',
     toltip='CircleMarker'

).add_to(m)

m

folium.Choropleth

Init signature:
folium.Choropleth(
    geo_data,
    data=None,
    columns=None,
    key_on=None,
    bins=6,
    fill_color=None,
    nan_fill_color='black',
    fill_opacity=0.6,
    nan_fill_opacity=None,
    line_color='black',
    line_weight=1,
    line_opacity=1,
    name=None,
    legend_name='',
    overlay=True,
    control=True,
    show=True,
    topojson=None,
    smooth_factor=None,
    highlight=None,
    use_jenks=False,
    **kwargs,
)
Docstring:     
Apply a GeoJSON overlay to the```

folium.Choropleth(
    geo_data='../data/02. us-states.json', #경계선 좌표가 담긴 데이터
    data=state_data, # Series or DataFrame
    columns=['State','Unemployment'],
    key_on='feature.id',
    fill_color='BuPu',
    fill_opacity=0.8, #0-1
    line_opacity=0.8, #0-1
    legend_name='Unemployment rate (#)'
).add_to(m)
    



m map.

```python
import json

state_data=pd.read_csv('../data/02. US_Unemployment_Oct2012.csv', encoding='utf-8')
state_data.tail(2)
-StateUnemployment
48WI6.8
49WY5.1

m=folium.Map([43,-102],zoom_start=3) 

folium.Choropleth(
    geo_data='../data/02. us-states.json', #경계선 좌표가 담긴 데이터
    data=state_data, # Series or DataFrame
    columns=['State','Unemployment'],
    key_on='feature.id',
    fill_color='BuPu',
    fill_opacity=0.8, #0-1
    line_opacity=0.8, #0-1
    legend_name='Unemployment rate (#)'
).add_to(m)
    

m


아파트 유형 지도 시각화

  • 공공데이터 포털
df=pd.read_csv('../data/02. 서울특별시 동작구_주택유형별 위치 정보 및 세대수 현황_20210825.csv',encoding='euc-kr') # 한글 파일은 euc-kr . cp949로 인코딩 
df.head()

-연번분류건물명행정동주소세대수위도경도
01아파트노량진우성노량진1동서울특별시 동작구 만양로8길 5090137.510304126.946866
12아파트노량진삼익노량진1동서울특별시 동작구 만양로 8417537.511367126.945226
23아파트신동아리버파크(분양 1,696,임대 925)노량진1동서울특별시 동작구 만양로 19262137.507073126.945718
34아파트노량진쌍용예가노량진1동서울특별시 동작구 장승배기로16길 13429937.510265126.943676
45아파트형인한강노량진1동서울특별시 동작구 만양로 367337.507664126.948235
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 167 entries, 0 to 166
Data columns (total 8 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   연번      167 non-null    int64  
 1   분류      167 non-null    object 
 2   건물명     167 non-null    object 
 3   행정동     167 non-null    object 
 4   주소      167 non-null    object 
 5   세대수     167 non-null    int64  
 6   위도      163 non-null    float64
 7   경도      163 non-null    float64
dtypes: float64(2), int64(2), object(4)
memory usage: 10.6+ KB
# NaN 데이터 제거
df=df.dropna()
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 163 entries, 0 to 166
Data columns (total 8 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   연번      163 non-null    int64  
 1   분류      163 non-null    object 
 2   건물명     163 non-null    object 
 3   행정동     163 non-null    object 
 4   주소      163 non-null    object 
 5   세대수     163 non-null    int64  
 6   위도      163 non-null    float64
 7   경도      163 non-null    float64
dtypes: float64(2), int64(2), object(4)
memory usage: 11.5+ KB
df.reset_index(drop=True).tail()
# 연변과 분류뒤에 빈칸 제거 
df=df.rename(columns={'연번 ':'연번','분류 ':'분류'})
df.columns

df.describe()
-세대수위도경도
count163.000000163.000000163.000000
mean371.92024537.497442126.949817
std413.1153540.0095320.019861
min21.00000037.477376126.906940
25%86.00000037.490626126.933284
50%199.00000037.496940126.949902
75%518.50000037.505321126.967196
max2621.00000037.514280126.981966
#folium
m=folium.Map(
    location=[ 37.495172947072,126.95453489844],
    zoom_start=13

)



for idx, rows in df.iterrows():
    # location
    lat,lng=rows.위도, rows.경도
    
    #icon - list >>> https://getbootstrap.com/docs/3.3/components/
    custom_icon=folium.Icon(
    color ='red' if rows.세대수>=199 else 'blue',
    icon_color='white',
    icon='home')
    
    #marker
    folium.Marker(
        location=[lat,lng],
        icon=custom_icon,
        tooltip=rows.분류,
        popup=rows.주소
    ).add_to(m)
    
    #ClickMarker
    folium.CircleMarker(
        location=[lat,lng],
        radius=rows.세대수*0.02,
        fill=True,
        color='#009dff' if rows.세대수<518 else '#ff0061',
        fill_color='#009dff'if rows.세대수<518 else '#ff0061'

    ).add_to(m)
    
m

2. 서울시 범죄 현환 지도 시각화

crime_anal_norm=pd.read_csv(
    '../data/02. crime_in_Seoul_final.csv', index_col=0,encoding='utf-8'
)
geo_path='../data/02. skorea_municipalities_geo_simple.json'
geo_str=json.load(open(geo_path,encoding='utf-8'))

crime_anal_norm.tail()
강도살인강간절도폭력강간검거율강도검거율살인검거율절도검거율폭력검거율인구수CCTV범죄검거
구별
용산구0.2307690.2857140.4864340.4056120.43711085.258964100.000000100.00000040.22834184.22818823373420960.36912881.943099
은평구0.2307690.4285710.3023260.4538270.48844991.02564177.777778100.00000053.42136986.63663747412421080.38078881.772285
종로구0.3076920.4285710.4612400.5284660.41492574.36974875.00000033.33333339.58762987.36190915199916190.42817961.930524
중구0.2051280.2142860.3837210.5856710.40795774.74747587.500000100.00000042.51162889.70786513076410230.35935378.893394
중랑구0.3589740.5714290.3178290.4606370.58012591.463415100.00000087.50000062.21170985.7142863911109160.45779985.377882
# 살인 발생 건수 시각화 

my_map=folium.Map(
    location=[37.5502,126.982],
    zoom_start=11,
    tiles='Stamen Toner'
)

folium.Choropleth(
    geo_data=geo_str, #우리나라 경계선 좌표가 답긴 데이터
    data=crime_anal_norm['살인'],
    columns=[crime_anal_norm.index,crime_anal_norm['살인']],
    key_on='feature.id',
    fill_color='PuRd',
    fill_opacity=0.8,
    line_opacity=0.5,
    legend_name='정규화된 살인 발생 건수'
).add_to(my_map)

my_map

# 5대 범죄 발생 건수 시각화 

my_map=folium.Map(
    location=[37.5502,126.982],
    zoom_start=11,
    tiles='Stamen Toner'
)

folium.Choropleth(
    geo_data=geo_str, #우리나라 경계선 좌표가 답긴 데이터
    data=crime_anal_norm['범죄'],
    columns=[crime_anal_norm.index,crime_anal_norm['범죄']],
    key_on='feature.id',
    fill_color='PuRd',
    fill_opacity=0.8,
    line_opacity=0.5,
    legend_name='정규화된 5대 범죄 발생 건수'
).add_to(my_map)

my_map

# 인구대비 범죄 발생 건수 시각화 

tmp_criminal=crime_anal_norm['범죄']/crime_anal_norm['인구수']

my_map=folium.Map(
    location=[37.5502,126.982],
    zoom_start=11,
    tiles='Stamen Toner'
)

folium.Choropleth(
    geo_data=geo_str, #우리나라 경계선 좌표가 답긴 데이터
    data=tmp_criminal,
    columns=[crime_anal_norm.index,tmp_criminal],
    key_on='feature.id',
    fill_color='PuRd',
    fill_opacity=0.8,
    line_opacity=0.5,
    legend_name='인구대비 범죄 발생 건수'
).add_to(my_map)

my_map

# 경찰서 별 범죄 발생 건수 시각화 

crime_anal_station=pd.read_csv(
    '../data/02. crime_in_Seoul_raw.csv',
    encoding='utf-8'
)
crime_anal_station.tail(2)
-구분강간검거강간발생강도검거강도발생살인검거살인발생절도검거절도발생폭력검거폭력발생구별latlng
29중부96.0141.03.03.02.02.0485.01204.01164.01335.0중구37.563646126.989580
30혜화64.0101.06.06.02.02.0379.0988.0842.0972.0종로구37.571840126.998856
col=['강간검거','강도검거','살인검거','절도검거','폭력검거']
tmp=crime_anal_station[col]/crime_anal_station[col].max() #정규화 0 - 1
crime_anal_station['검거']=np.mean(tmp,axis=1) # numpy axis = 1 >> 행을 말함 / pandas axis = 1 >> 열을말함 
crime_anal_station.tail()
구분강간검거강간발생강도검거강도발생살인검거살인발생절도검거절도발생폭력검거폭력발생구별latlng검거
26종로113.0137.03.06.00.04.0389.0952.01135.01291.0종로구37.575558126.9848670.238103
27종암42.051.05.05.01.02.0344.0680.0815.0932.0성북구37.602059127.0321580.195242
28중랑150.0164.014.014.07.08.01052.01691.02712.03164.0중랑구37.618692127.1047140.675873
29중부96.0141.03.03.02.02.0485.01204.01164.01335.0중구37.563646126.9895800.277182
30혜화64.0101.06.06.02.02.0379.0988.0842.0972.0종로구37.571840126.9988560.240065
# 경찰서 위치 마커 표시 
my_map=folium.Map(
    location=[37.5502, 126.982],
    zoom_start=11
)



for idx, rows in crime_anal_station.iterrows():

    folium.Marker(
        location=[rows['lat'],rows['lng']]
    
    ).add_to(my_map)
    
my_map

# Circle 추가 : 검거에 값을 곱한 뒤 원의 넓이 적용

my_map=folium.Map(
    location=[37.5502, 126.982],
    zoom_start=11
)

for idx, rows in crime_anal_station.iterrows():

    folium.CircleMarker(
        location=[rows['lat'],rows['lng']],
        radius=rows['검거']*50,
        popup=rows['구분'] + ' : '+'%.2f ' %rows['검거'],
        fill=True,
        color='#3186cc',
        fill_color='3186cc'
    
    ).add_to(my_map)
    
my_map

# 경계선 추가

my_map=folium.Map(
    location=[37.5502, 126.982],
    zoom_start=11
)

folium.Choropleth(
    geo_data=geo_str,
    data=crime_anal_norm['범죄'],
    columns=[crime_anal_norm.index,crime_anal_norm['범죄']],
    key_on='feature.id',
    fill_color='PuRd',
    fill_opacity=0.7,
    line_opacity=0.2,
    
).add_to(my_map) 

my_map

3. 서울시 범죄현황 발생 장소 분석

#추가 검증

crime_loc_raw=pd.read_csv(
    '../data/02. crime_in_Seoul_location.csv', thousands=',',encoding='euc-kr'
)
crime_loc_raw.tail()
-범죄명장소발생건수
60폭력교통수단222
61폭력유원지424
62폭력학교203
63폭력금융기관42
64폭력기타26382
crime_loc_raw.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 65 entries, 0 to 64
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   범죄명     65 non-null     object
 1   장소      65 non-null     object
 2   발생건수    65 non-null     int64 
dtypes: int64(1), object(2)
memory usage: 1.6+ KB
crime_loc=crime_loc_raw.pivot_table(
    values=crime_loc_raw, index='장소', columns='범죄명', aggfunc=[np.sum]
)
crime_loc.columns=crime_loc.columns.droplevel([0,1])
crime_loc
범죄명강간.추행강도살인절도폭력
장소
교통수단69100457222
금융기관211108142
기타212867652173426382
노상9868722932924535
단독주택395153022413579
사무실132816821229
상점953414403852
숙박업소, 목욕탕38994828303
아파트, 연립 다세대284181215042839
역, 대합실18100356272
유원지5922367424
유흥 접객업소39813820352645
학교3300400203
col=['살인','강도','강간','절도','폭력']
crime_loc_norm=crime_loc / crime_loc.max() # 정규화
crime_loc_norm['종합'] = np.mean(crime_loc_norm, axis=1)
crime_loc_norm
범죄명강간.추행강도살인절도폭력종합
장소
교통수단0.3247180.0000000.0000000.0210270.0084150.070832
금융기관0.0009400.0114940.0153850.0497380.0015920.015830
기타1.0000000.7701151.0000001.0000001.0000000.954023
노상0.4633461.0000000.3384620.4292350.9299900.632207
단독주택0.1856200.1724140.4615380.1031100.1356610.211669
사무실0.0620300.0919540.0153850.0313790.0465850.049467
상점0.0446430.3908050.0153850.2025860.0322950.137143
숙박업소, 목욕탕0.1828010.1034480.0615380.0380970.0114850.079474
아파트, 연립 다세대0.1334590.2068970.1846150.0692000.1076110.140356
역, 대합실0.0850560.0000000.0000000.0163800.0103100.022349
유원지0.0277260.0229890.0307690.0168860.0160720.022888
유흥 접객업소0.1870300.1494250.1230770.0936320.1002580.130684
학교0.0155080.0000000.0000000.0184040.0076950.008321
crime_loc_norm_sort=crime_loc_norm.sort_values('종합',ascending=False) #내림차순 

def drawGraph():
    plt.figure(figsize=(10,10))
    sns.heatmap(
        crime_loc_norm_sort,
        annot=True,
        fmt='f',
        linewidths=0.5,
        cmap='RdPu')
    
    plt.title('범죄 발생 장소')
    plt.show()
    
drawGraph()

profile
개발하고싶은사람

0개의 댓글