Plotly Bubble chart animation 만들기
Bubble차트를 animation으로 표현하는 방법을 정리합니다. 데이터는 gapminder
를 사용합니다.
import plotly.express as px
df = px.data.gapminder()
df.sample(5 )
379
Croatia
Europe
1987
71.520
4484310
13822.583940
HRV
191
1222
Philippines
Asia
2002
70.303
82995088
2650.921068
PHL
608
1119
Niger
Africa
1967
40.118
4534062
1054.384891
NER
562
1662
West Bank and Gaza
Asia
1982
64.406
1425876
4336.032082
PSE
275
49
Argentina
Americas
1957
64.399
19610538
6856.856212
ARG
32
데이터를 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
정보를 확인할 수 있습니다.