Plotly Bubble chart animation 만들기
Bubble차트를 animation으로 표현하는 방법을 정리합니다. 데이터는 gapminder
를 사용합니다.
import plotly.express as px
df = px.data.gapminder()
df.sample(5 )
1425
Spain
Europe
1997
78.770
39855442
20445.298960
ESP
724
1077
Nepal
Asia
1997
59.426
23001113
1010.892138
NPL
524
956
Mali
Africa
1992
48.388
8416215
739.014375
MLI
466
1400
Somalia
Africa
1992
39.658
6099799
926.960296
SOM
706
1136
Nigeria
Africa
1992
47.472
93364244
1619.848217
NGA
566
데이터를 Animation으로 보여주기 위해서 데이터프레임의 정보를 확인합니다.
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1704 entries, 0 to 1703
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 country 1704 non-null object
1 continent 1704 non-null object
2 year 1704 non-null int64
3 lifeExp 1704 non-null float64
4 pop 1704 non-null int64
5 gdpPercap 1704 non-null float64
6 iso_alpha 1704 non-null object
7 iso_num 1704 non-null int64
dtypes: float64(2), int64(3), object(3)
memory usage: 106.6+ KB
데이터프레임의 year
컬럼을 이용해서 연도별 흐름을 animation으로 표현할 수 있을 것 같습니다. 좀 더 자세히 year
컬럼을 확인합니다.
display(len (df['year' ].unique()))
fig = px.histogram(df, x= 'year' , nbins = 60 )
fig.show()
데이터프레임의 year
컬럼은 총 12개의 unique value를 갖고 있습니다. 히스토그램으로 표시하면 5년 단위로 값을 갖는 것을 알 수 있습니다. 이제 year
정보를 이용해서 animation을 구성합니다.
fig = px.scatter(df, x= 'gdpPercap' , y= 'lifeExp' , color= 'continent' , size= 'pop' ,
hover_name= 'country' , log_x= True , animation_frame= 'year' ,
animation_group= 'country' , range_x= [100 , 70000 ], range_y= [25 ,90 ])
fig.show()
시간의 흐름에 따라서 x축과 y축에 표시되는 데이터의 위치가 변경됩니다. 데이터가 최초와 최종 animation단계에서 모두 그래프에 표시될 수 있도록 range_x
와 range_y
를 이용하여 축의 범위를 수정합니다.
fig = px.bar(df, x= "continent" , y= "pop" , color= "continent" , hover_name= 'country' ,
animation_frame= "year" , animation_group= "country" , range_y= [0 ,4000000000 ])
fig.show()
위와 같이 Bar차트도 동일하게 animation_frame
과 animation_group
을 설정하여 시간의 흐름에 따른 인구 변화를 나타낼 수 있습니다. hover_name
을 country
로 설정해서 animation_group
의 country
정보를 확인할 수 있습니다.