데이터 시각화

Azure Synapse는 데이터 웨어하우스 및 빅 데이터 분석 시스템에서 인사이트 시간을 가속화하는 통합 분석 서비스입니다. 데이터 시각화는 데이터에 대한 인사이트를 얻을 수 있는 핵심 구성 요소입니다. 이를 통해 크고 작은 데이터를 더 쉽게 이해할 수 있습니다. 또한 데이터 그룹에서 패턴, 추세 및 이상값을 더 쉽게 검색할 수 있습니다.

Azure Synapse Analytics에서 Apache Spark를 사용하는 경우 Synapse Notebook 차트 옵션, 인기 있는 오픈 소스 라이브러리에 대한 액세스, Synapse SQL 및 Power BI와의 통합 등 데이터를 시각화하는 데 도움이 되는 다양한 기본 제공 옵션이 있습니다.

전자 필기장 차트 옵션

Azure Synapse Notebook을 사용하는 경우 차트 옵션을 사용하여 테이블 형식 결과 보기를 사용자 지정된 차트로 전환할 수 있습니다. 여기서는 코드를 작성하지 않고도 데이터를 시각화할 수 있습니다.

display(df) 함수

display 함수를 사용하면 SQL 쿼리와 Apache Spark 데이터 프레임 및 RDD를 풍부한 데이터 시각화로 전환할 수 있습니다. 이 함수는 display PySpark, Scala, Java, R 및 .NET에서 만든 데이터 프레임 또는 RDD에서 사용할 수 있습니다.

차트 옵션에 액세스하려면 다음을 수행합니다.

  1. 매직 명령의 %%sql 출력은 기본적으로 렌더링된 테이블 뷰에 표시됩니다. Spark DataFrames 또는 RDD(Resilient Distributed Datasets) 함수를 호출 display(df) 하여 렌더링된 테이블 뷰를 생성할 수도 있습니다.

  2. 렌더링된 테이블 보기가 있으면 차트 보기로 전환합니다. 기본 제공 차트

  3. 이제 다음 값을 지정하여 시각화를 사용자 지정할 수 있습니다.

    Configuration 설명
    차트 종류 display 함수는 막대형 차트, 산점도, 꺾은선형 그래프 등을 포함한 다양한 차트 종류를 지원합니다.
    암호키 x축의 값 범위 지정
    가치 y축 값의 값 범위 지정
    계열 그룹 집계에 대한 그룹을 확인하는 데 사용됩니다.
    Aggregation 시각화에서 데이터를 집계하는 방법

    메모

    기본적으로 함수는 display(df) 데이터의 처음 1000개 행만 사용하여 차트를 렌더링합니다. 모든 결과에 대한 집계를 확인하고 적용 단추를 클릭하면 전체 데이터 세트에서 차트 생성이 적용됩니다. 차트 설정이 변경되면 Spark 작업이 트리거됩니다. 계산을 완료하고 차트를 렌더링하는 데 몇 분 정도 걸릴 수 있습니다.

  4. 완료되면 최종 시각화를 보고 상호 작용할 수 있습니다.

display(df) 통계 세부 정보

열 이름, 열 형식, 고유 값 및 각 열에 대한 누락된 값을 포함하는 지정된 Apache Spark DataFrame의 통계 요약을 확인하는 데 사용할 display(df, summary = true) 수 있습니다. 특정 열을 선택하여 최소값, 최대값, 평균 값 및 표준 편차를 확인할 수도 있습니다. 기본 제공 차트 요약

displayHTML() 옵션

Azure Synapse Analytics 노트북은 displayHTML 함수를 사용하여 HTML 그래픽을 지원합니다.

다음 이미지는 D3.js를 사용하여 시각화를 만드는 방법의 예제입니다.

d3-js-example

다음 코드를 실행하여 위의 시각화를 만듭니다.

displayHTML("""<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
  width = 400 - margin.left - margin.right,
  height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
.append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// Create Data
var data = [12,19,11,13,12,22,13,4,15,16,18,19,20,12,11,9]

// Compute summary statistics used for the box:
var data_sorted = data.sort(d3.ascending)
var q1 = d3.quantile(data_sorted, .25)
var median = d3.quantile(data_sorted, .5)
var q3 = d3.quantile(data_sorted, .75)
var interQuantileRange = q3 - q1
var min = q1 - 1.5 * interQuantileRange
var max = q1 + 1.5 * interQuantileRange

// Show the Y scale
var y = d3.scaleLinear()
  .domain([0,24])
  .range([height, 0]);
svg.call(d3.axisLeft(y))

// a few features for the box
var center = 200
var width = 100

// Show the main vertical line
svg
.append("line")
  .attr("x1", center)
  .attr("x2", center)
  .attr("y1", y(min) )
  .attr("y2", y(max) )
  .attr("stroke", "black")

// Show the box
svg
.append("rect")
  .attr("x", center - width/2)
  .attr("y", y(q3) )
  .attr("height", (y(q1)-y(q3)) )
  .attr("width", width )
  .attr("stroke", "black")
  .style("fill", "#69b3a2")

// show median, min and max horizontal lines
svg
.selectAll("toto")
.data([min, median, max])
.enter()
.append("line")
  .attr("x1", center-width/2)
  .attr("x2", center+width/2)
  .attr("y1", function(d){ return(y(d))} )
  .attr("y2", function(d){ return(y(d))} )
  .attr("stroke", "black")
</script>

"""
)

Python 라이브러리

데이터 시각화와 관련하여 Python은 다양한 기능이 포함된 여러 그래프 라이브러리를 제공합니다. 기본적으로 Azure Synapse Analytics의 모든 Apache Spark 풀에는 큐레이팅되고 인기 있는 오픈 소스 라이브러리 집합이 포함되어 있습니다. Azure Synapse Analytics 라이브러리 관리 기능을 사용하여 추가 라이브러리 및 버전을 추가하거나 관리할 수도 있습니다.

Matplotlib

각 라이브러리에 기본 제공되는 렌더링 함수를 사용하여 Matplotlib 같은 표준 그리기 라이브러리를 렌더링할 수 있습니다.

다음 이미지는 Matplotlib를 사용하여 막대형 차트를 만드는 방법의 예제입니다. 꺾은선형 그래프 예제.

위의 이미지를 그리려면 다음 샘플 코드를 실행합니다.

# Bar chart

import matplotlib.pyplot as plt

x1 = [1, 3, 4, 5, 6, 7, 9]
y1 = [4, 7, 2, 4, 7, 8, 3]

x2 = [2, 4, 6, 8, 10]
y2 = [5, 6, 2, 6, 2]

plt.bar(x1, y1, label="Blue Bar", color='b')
plt.bar(x2, y2, label="Green Bar", color='g')
plt.plot()

plt.xlabel("bar number")
plt.ylabel("bar height")
plt.title("Bar Chart Example")
plt.legend()
plt.show()

보케 (Bokeh)

를 사용하여 HTML 또는 대화형 라이브러리(예: bokeh)를 렌더링할 displayHTML(df)수 있습니다.

다음 이미지는 빛망울을 사용하여 지도 위에 문자 모양을 그리는 예입니다.

bokeh-example

위의 이미지를 그리려면 다음 샘플 코드를 실행합니다.

from bokeh.plotting import figure, output_file
from bokeh.tile_providers import get_provider, Vendors
from bokeh.embed import file_html
from bokeh.resources import CDN
from bokeh.models import ColumnDataSource

tile_provider = get_provider(Vendors.CARTODBPOSITRON)

# range bounds supplied in web mercator coordinates
p = figure(x_range=(-9000000,-8000000), y_range=(4000000,5000000),
           x_axis_type="mercator", y_axis_type="mercator")
p.add_tile(tile_provider)

# plot datapoints on the map
source = ColumnDataSource(
    data=dict(x=[ -8800000, -8500000 , -8800000],
              y=[4200000, 4500000, 4900000])
)

p.circle(x="x", y="y", size=15, fill_color="blue", fill_alpha=0.8, source=source)

# create an html document that embeds the Bokeh plot
html = file_html(p, CDN, "my plot1")

# display this html
displayHTML(html)

Plotly

displayHTML()을 사용하여 Plotly 같은 대화형 라이브러리 또는 HTML을 렌더링할 수 있습니다.

다음 샘플 코드를 실행하여 아래 이미지를 그립니다.

plotly-example

from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                   dtype={"fips": str})

import plotly
import plotly.express as px

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                           color_continuous_scale="Viridis",
                           range_color=(0, 12),
                           scope="usa",
                           labels={'unemp':'unemployment rate'}
                          )
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

# create an html document that embeds the Plotly plot
h = plotly.offline.plot(fig, output_type='div')

# display this html
displayHTML(h)

Pandas

pandas 데이터 프레임의 html 출력을 기본 출력으로 볼 수 있습니다. Notebook은 스타일이 지정된 html 콘텐츠를 자동으로 표시합니다.

Panda 그래프 예제입니다.

import pandas as pd 
import numpy as np 

df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]], 

                  index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'), 

                  columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:'])) 

df 

추가 라이브러리

이러한 라이브러리 외에도 Azure Synapse Analytics 런타임에는 데이터 시각화에 자주 사용되는 다음 라이브러리 집합도 포함되어 있습니다.

사용 가능한 라이브러리 및 버전에 대한 최신 정보는 Azure Synapse Analytics 런타임 설명서를 참조하세요.

R 라이브러리(미리 보기)

R 에코시스템은 다양한 기능으로 가득 찬 여러 그래프 라이브러리를 제공합니다. 기본적으로 Azure Synapse Analytics의 모든 Apache Spark 풀에는 큐레이팅되고 인기 있는 오픈 소스 라이브러리 집합이 포함되어 있습니다. Azure Synapse Analytics 라이브러리 관리 기능을 사용하여 추가 라이브러리 및 버전을 추가하거나 관리할 수도 있습니다.

ggplot2

ggplot2 라이브러리는 데이터 시각화 및 탐색적 데이터 분석에 널리 사용됩니다.

ggplot2 그래프 예제의 스크린샷

library(ggplot2)
data(mpg, package="ggplot2") 
theme_set(theme_bw()) 

g <- ggplot(mpg, aes(cty, hwy))

# Scatterplot
g + geom_point() + 
  geom_smooth(method="lm", se=F) +
  labs(subtitle="mpg: city vs highway mileage", 
       y="hwy", 
       x="cty", 
       title="Scatterplot with overlapping points", 
       caption="Source: midwest")

rBokeh

rBokeh는 Bokeh 시각화 라이브러리에서 지원되는 대화형 그래픽을 만들기 위한 네이티브 R 그리기 라이브러리입니다.

rBokeh를 설치하려면 다음 명령을 사용할 수 있습니다.

install.packages("rbokeh")

설치되면 rBokeh를 활용하여 대화형 시각화를 만들 수 있습니다.

rBokeh 그래프 예제의 스크린샷.

library(rbokeh)
p <- figure() %>%
  ly_points(Sepal.Length, Sepal.Width, data = iris,
    color = Species, glyph = Species,
    hover = list(Sepal.Length, Sepal.Width))

R Plotly

Plotly's R 그래프 라이브러리는 대화형, 출판 품질의 그래프를 생성합니다.

Plotly를 설치하려면 다음 명령을 사용할 수 있습니다.

install.packages("plotly")

설치되면 Plotly를 활용하여 대화형 시각화를 만들 수 있습니다.

Plotly 그래프 예시의 스크린샷.

library(plotly) 

fig <- plot_ly() %>% 
  add_lines(x = c("a","b","c"), y = c(1,3,2))%>% 
  layout(title="sample figure", xaxis = list(title = 'x'), yaxis = list(title = 'y'), plot_bgcolor = "#c7daec") 

fig

Highcharter

Highcharter 는 Highcharts JavaScript 라이브러리 및 해당 모듈에 대한 R 래퍼입니다.

Highcharter를 설치하려면 다음 명령을 사용할 수 있습니다.

install.packages("highcharter")

설치되면 Highcharter를 활용하여 대화형 시각화를 만들 수 있습니다.

Highcharter 그래프 예제의 스크린샷

library(magrittr)
library(highcharter)
hchart(mtcars, "scatter", hcaes(wt, mpg, z = drat, color = hp)) %>%
  hc_title(text = "Scatter chart with size and color")

Apache Spark 및 SQL 온디맨드를 사용하여 Power BI에 연결

Azure Synapse Analytics는 Power BI와 긴밀하게 통합되어 데이터 엔지니어가 분석 솔루션을 빌드할 수 있도록 합니다.

Azure Synapse Analytics를 사용하면 다양한 작업 영역 계산 엔진이 Spark 풀과 서버리스 SQL 풀 간에 데이터베이스와 테이블을 공유할 수 있습니다. 공유 메타데이터 모델을 사용하여 SQL 주문형을 사용하여 Apache Spark 테이블을 쿼리할 수 있습니다. 완료되면 SQL 주문형 엔드포인트를 Power BI에 연결하여 동기화된 Spark 테이블을 쉽게 쿼리할 수 있습니다.

다음 단계