Lets-Plot으로 데이터 시각화하기
Lets-Plot으로 데이터 시각화하기
Lets-Plot for Kotlin(LPK)은 R의 ggplot2 라이브러리를 Kotlin으로 포팅한 멀티플랫폼 플로팅 라이브러리입니다. LPK는 기능이 풍부한 ggplot2 API를 Kotlin 생태계에 가져와서, 정교한 데이터 시각화 기능이 필요한 과학자와 통계학자에게 적합합니다.
LPK는 Kotlin/JS, JVM의 Swing, JavaFX, Compose Multiplatform을 비롯한 다양한 플랫폼을 지원합니다. 또한 IntelliJ, DataGrip, DataSpell, PyCharm과 자연스럽게 통합됩니다.
이 튜토리얼에서는 IntelliJ IDEA에서 LPK 라이브러리와 Kotlin DataFrame 라이브러리를 이용해 다양한 플롯(plot)을 만드는 방법을 보여드릴게요.
본문
시작하기 전에
IntelliJ IDEA 2026.2부터 Kotlin Notebook은 더 이상 IDE에 번들로 포함되지 않고 JetBrains에서 공식 지원되지 않습니다. 소스 코드는 GitHub에서 계속 이용할 수 있습니다.
자세한 내용은 블로그 게시물에서 확인해 보세요.
Lets-Plot으로 작업하려면 새 Kotlin Notebook을 만들어 주세요:
-
File | New | Kotlin Notebook을 선택합니다.
-
노트북에서 다음 명령을 실행하여 LPK와 Kotlin DataFrame 라이브러리를 임포트합니다:
%use lets-plot %use dataframe
튜토리얼을 따라 하려면 DataFrame을 Gradle이나 Maven 의존성으로도 사용할 수 있습니다.
데이터 준비하기
베를린(Berlin), 마드리드(Madrid), 카라카스(Caracas) 세 도시의 월평균 기온에 대한 시뮬레이션 숫자를 저장하는 DataFrame을 만들어 볼게요.
Kotlin DataFrame 라이브러리의 dataFrameOf() 함수를 사용해 DataFrame을 생성합니다. 다음 코드 스니펫을 붙여 넣고 실행해 주세요:
// The months variable stores a list with 12 months of the year
val months = listOf(
"January", "February",
"March", "April", "May",
"June", "July", "August",
"September", "October", "November",
"December"
)
// The tempBerlin, tempMadrid, and tempCaracas variables store a list with temperature values for each month
val tempBerlin =
listOf(-0.5, 0.0, 4.8, 9.0, 14.3, 17.5, 19.2, 18.9, 14.5, 9.7, 4.7, 1.0)
val tempMadrid =
listOf(6.3, 7.9, 11.2, 12.9, 16.7, 21.1, 24.7, 24.2, 20.3, 15.4, 9.9, 6.6)
val tempCaracas =
listOf(27.5, 28.9, 29.6, 30.9, 31.7, 35.1, 33.8, 32.2, 31.3, 29.4, 28.9, 27.6)
// The df variable stores a DataFrame of three columns, including monthly records, temperature, and cities
val df = dataFrameOf(
"Month" to months + months + months,
"Temperature" to tempBerlin + tempMadrid + tempCaracas,
"City" to List(12) { "Berlin" } + List(12) { "Madrid" } + List(12) { "Caracas" }
)
df.head(4)
DataFrame에 Month, Temperature, City 세 개의 컬럼이 있는 것을 확인할 수 있겠죠. DataFrame의 처음 네 행에는 1월부터 4월까지 베를린의 기온 기록이 들어 있습니다.
LPK 라이브러리로 플롯을 만들려면 데이터(df)를 키-값 쌍으로 저장하는 Map 타입으로 변환해야 합니다. .toMap() 함수를 사용하면 DataFrame을 쉽게 Map으로 변환할 수 있어요:
val data = df.toMap()
산점도 만들기
LPK 라이브러리로 산점도(scatter plot)를 만들어 볼게요.
데이터가 Map 형식이 되면 LPK 라이브러리의 geomPoint() 함수를 사용해 산점도를 생성합니다. X축과 Y축 값을 지정하고, 카테고리와 그 색상도 정의할 수 있어요. 추가로 플롯의 크기와 점 모양도 필요에 맞게 커스터마이즈할 수 있습니다:
// Specifies X and Y axes, categories and their color, plot size, and plot type
val scatterPlot =
letsPlot(data) { x = "Month"; y = "Temperature"; color = "City" } + ggsize(600, 500) + geomPoint(shape = 15)
scatterPlot
결과는 다음과 같습니다:
박스 플롯 만들기
앞서 만든 데이터를 박스 플롯(box plot)으로 시각화해 볼게요. LPK 라이브러리의 geomBoxplot() 함수로 플롯을 생성하고, scaleFillManual() 함수로 색상을 커스터마이즈합니다:
// Specifies X and Y axes, categories, plot size, and plot type
val boxPlot = ggplot(data) { x = "City"; y = "Temperature" } + ggsize(700, 500) + geomBoxplot { fill = "City" } +
// Customizes colors
scaleFillManual(values = listOf("light_yellow", "light_magenta", "light_green"))
boxPlot
결과는 다음과 같습니다:
2D 밀도 플롯 만들기
이제 임의의 데이터의 분포와 밀집도를 시각화하기 위해 2D 밀도 플롯(2D density plot)을 만들어 볼게요.
2D 밀도 플롯을 위한 데이터 준비
-
데이터를 처리하고 플롯을 생성하기 위한 의존성을 임포트합니다:
%use lets-plot @file:DependsOn("org.apache.commons:commons-math3:3.6.1") import org.apache.commons.math3.distribution.MultivariateNormalDistribution -
다음 코드 스니펫을 붙여 넣고 실행해 2D 데이터 포인트 집합을 만듭니다:
// Defines covariance matrices for three distributions val cov0: Array<DoubleArray> = arrayOf( doubleArrayOf(1.0, -.8), doubleArrayOf(-.8, 1.0) ) val cov1: Array<DoubleArray> = arrayOf( doubleArrayOf(1.0, .8), doubleArrayOf(.8, 1.0) ) val cov2: Array<DoubleArray> = arrayOf( doubleArrayOf(10.0, .1), doubleArrayOf(.1, .1) ) // Defines the number of samples val n = 400 // Defines means for three distributions val means0: DoubleArray = doubleArrayOf(-2.0, 0.0) val means1: DoubleArray = doubleArrayOf(2.0, 0.0) val means2: DoubleArray = doubleArrayOf(0.0, 1.0) // Generates random samples from three multivariate normal distributions val xy0 = MultivariateNormalDistribution(means0, cov0).sample(n) val xy1 = MultivariateNormalDistribution(means1, cov1).sample(n) val xy2 = MultivariateNormalDistribution(means2, cov2).sample(n)위 코드에서
xy0,xy1,xy2변수는 2D(x, y) 데이터 포인트 배열을 저장합니다. -
데이터를
Map타입으로 변환합니다:val data = mapOf( "x" to (xy0.map { it[0] } + xy1.map { it[0] } + xy2.map { it[0] }).toList(), "y" to (xy0.map { it[1] } + xy1.map { it[1] } + xy2.map { it[1] }).toList() )
2D 밀도 플롯 생성하기
이전 단계의 Map을 사용해, 데이터 포인트와 이상치(outlier)를 더 잘 시각화하기 위해 배경에 산점도(geomPoint)를 깔고 2D 밀도 플롯(geomDensity2D)을 만듭니다. scaleColorGradient() 함수로 색상 스케일을 커스터마이즈할 수 있어요:
val densityPlot = letsPlot(data) { x = "x"; y = "y" } + ggsize(600, 300) + geomPoint(
color = "black",
alpha = .1
) + geomDensity2D { color = "..level.." } +
scaleColorGradient(low = "dark_green", high = "yellow", guide = guideColorbar(barHeight = 10, barWidth = 300)) +
theme().legendPositionBottom()
densityPlot
결과는 다음과 같습니다:
더 알아보기
- Lets-Plot for Kotlin 문서에서 더 많은 플롯 예제를 살펴보세요.
- Lets-Plot for Kotlin의 API 레퍼런스를 확인해 보세요.
- Kotlin DataFrame과 Kandy 라이브러리 문서에서 Kotlin으로 데이터를 변환하고 시각화하는 방법을 배워 보세요.
- Data visualization with Kandy
- Kotlin and Java libraries for data analysis