Anda di halaman 1dari 11

Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

Jobsheet 8
Data Visualization
Kompetensi Dasar
• Mahasiswa dapat menampilkan data dalam berbagai bentuk.

Visuailisasi Data

Visualisasi data adalah hal yang sangat penting mengingat manusiaadalah makhluk visual, 80%
orang lebih mudah memahami sesuatu secara visual. Dengan adanya visualisasi data ini, mulai
dari pengambilan keputusan sampai evaluasi dapat dipahami dengan lebih baik.

Pengertian

Visualisasi data adalah tampilan berupa grafis atau visual dari informasi dan data. Dengan kata
lain, Visualisasi data adalah proses dimana kumpulan data diubah menjadi bentuk visual yang
lebih sederhana untuk ditampilkan.

Elemen visual yang digunakan akan mempermudah pembaca untuk memahami tren, outliers,
dan pola dalam suatu data. Dari pemahaman tersebut, dapat dilakukan analisis dan pemahaman
yang lebih mengennai data yang ada untuk evaluasi dan pengambilan keputusan.

Kegunaan

Salah satu kegunaan Visualisasi data adalah untuk mempermudah komunikasi antar stakeholder
atau orang lain yang tidak berhubungan langsung dengan data tersebut. Visualisasi data
memberikan informasi yang sangat berguna di banyak bidang. Dengan variabel-variabel yang
ada, pengambilan keputusan dapat dilakukan dengan mudah.

Visuailisasi data juga sangat berguna untuk analisis, dimana banyak sekali informasi yang bisa
di dapat dengan memvisualisasikan data disbanding dengan data mentah. Dengan begitu,
pemahaman tentang data tersebut akan jauh lebih dalam.
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

Macam-macam Visualisasi Data

Dengan berbagai macam bentuk data, maka beragam juga cara untuk memvisualisasikan data.

1. Temporal
Visualisasi Temporal cocok untuk menunjukan data yang berbentuk linear atau satu
dimensi. Ciri utama dari Visualisasi temporal adalah garis yang bermulai dan berakhir di
titik tertentu. Garis tersebut dapat berdisi sendiri ataupun bersinggungan dengan garis
lainnya.
Contohnya adalah diagram scatterplot, timeline, time series, dan diagram garis.

2. Hierarki
Visualisasi hierarki umum digunakan untuk menunjukan hubungan antara kumpulan data
dengan kumpulan data lainnya. hubungan antar data tersebut dapat sama besar, lebih
besar, ataupun lebih kecil. Visualisasi ini berguna untuk menunjukan data-data baru yang
muncul karena suatu sebab.
Contohnya adalah diagram pohon.
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

3. Network
Visualisasi network digunakan unutk mempermudah memahami hubungan antar dataset,
karena dataset sendiri dapat berpengaruh satu sama lain.
Contohnya adalah world cloud dan node-link diagram.

4. Multidimensi
Visualisasi multidimensi cocok untuk menampilkan data yang memiliki banyak dimensi
atau variabel. Karena data yang sangat banyak, biasanya data yang ditampilkan dengan
visualisasi ini dibuat mencolok dan menarik mata.
Contohnya adalah histogram, pie chart, dan stacked-bar.
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

5. Geospasial
Visualisasi geospasial merepresentasikan wujud nyata dari suatu benda, lokasi, atau
ruang yang memiliki data. Umumnya geospasial digunakan untuk membedakan data
pada setiap wilayah.
Contohnya adalah heatmap, dan kartograf.
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

Praktikum
1. Visualisasi Data

# Making sense of data through advance visualization


%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pandas.tools.rplot as rplot

## Controlling the line properties of a chart


#Let create a simple line chart
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

#Increasing the line width


plt.plot([1, 2, 3, 4], [1, 4, 9, 16], linewidth=4.0)
plt.show()

#Setting the dashed lines


line, = plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
line.set_linestyle('-.')
plt.show()

#setting the color and width of the line


line, = plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.setp(line, color='r', linewidth=2.0)
plt.show()

#Plotting multiple plots


p1 = np.arange(0.0, 30.0, 0.1)
plt.subplot(211)
plt.plot(p1, np.sin(p1)/p1, 'b--')

plt.subplot(212)
plt.plot(p1, np.cos(p1), 'r--')
plt.show()

#Playing with text


n = np.random.random_sample((5,))
plt.bar(np.arange(len(n)), n)
plt.xlabel('Indices')
plt.ylabel('Value')
plt.text(1, .7, r'$\mu=' + str(np.round(np.mean(n), 2)) + ' $')
plt.show()
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

#Annotating the text


ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)


s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),


arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()

#Styling your plots


#Creating a simple line chart with the ggplot style
plt.style.use('ggplot')
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

# Using the fivethirtyeight.com style


plt.style.use('fivethirtyeight')
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

#Temporary styling
with plt.style.context(('dark_background')):
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

#Box plots
#Lets add some data and plot the box plot
## Creating some data
np.random.seed(10)
box_data_1 = np.random.normal(100, 10, 200)
box_data_2 = np.random.normal(80, 30, 200)
box_data_3 = np.random.normal(90, 20, 200)

## Combining the different data in a list


data_to_plot = [box_data_1, box_data_2, box_data_3]

# Create the boxplot


bp = plt.boxplot(data_to_plot)
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

#Change the color of the boxes and customize the whiskers


## add patch_artist=True option to ax.boxplot()
## to get fill color
bp = plt.boxplot(data_to_plot, patch_artist=True)

## change outline color, fill color and linewidth of the boxes


for box in bp['boxes']:
# change outline color
box.set( color='#7570b3', linewidth=2)
# change fill color
box.set( facecolor = '#1b9e77' )

## change color and linewidth of the whiskers


for whisker in bp['whiskers']:
whisker.set(color='#7570b3', linewidth=2)

## change color and linewidth of the caps


for cap in bp['caps']:
cap.set(color='#7570b3', linewidth=2)

## change color and linewidth of the medians


for median in bp['medians']:
median.set(color='#b2df8a', linewidth=2)

## change the style of fliers and their fill


for flier in bp['fliers']:
flier.set(marker='o', color='#e7298a', alpha=0.5)

#Heat Maps
#Adding some data

# Generate Data
data = np.random.rand(10,6)
rows = list('ZYXWVUTSRQ')
columns = list('ABCDEF')

#We'll use the pcolor() which is similar to heatmaps.2() in R

plt.pcolor(data)
plt.show()

#We'll add the row and column labels to the heat map
# Add Row/Column Labels
plt.pcolor(data)
plt.xticks(np.arange(0,6)+0.5,columns)
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

plt.yticks(np.arange(0,10)+0.5,rows)
plt.show()
plt.close()

#Now, we'll change the color of the heatmap

# Change color map


plt.pcolor(data,cmap=plt.cm.Reds,edgecolors='k')
plt.xticks(np.arange(0,6)+0.5,columns)
plt.yticks(np.arange(0,10)+0.5,rows)
plt.show()

#For a large amount of values that needs to be visualized using the heatmap

# Generate some test data


x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)


extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap, extent=extent)
plt.show()

##Scatter plot with Histogram

from matplotlib.ticker import NullFormatter

# the random data


x = np.random.randn(1000)
y = np.random.randn(1000)

nullfmt = NullFormatter() # no labels

# definitions for the axes


left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left+width+0.02

rect_scatter = [left, bottom, width, height]


rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

# start with a rectangular Figure


plt.figure(1, figsize=(8,8))

axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)

# no labels
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)

# the scatter plot:


axScatter.scatter(x, y)

# now determine nice limits by hand:


binwidth = 0.25
xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth

axScatter.set_xlim( (-lim, lim) )


axScatter.set_ylim( (-lim, lim) )

bins = np.arange(-lim, lim + binwidth, binwidth)


axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')

axHistx.set_xlim( axScatter.get_xlim() )
axHisty.set_ylim( axScatter.get_ylim() )

plt.show()

#Scatter Matrix
df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
spm = pd.plotting.scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='hist')

#Creating the scatter plot with the Kernal Density Estimation


spm = pd.tools.plotting.scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')

##Area Plot
#The area plot below is basically stacked across the instances
df = pd.DataFrame(np.random.rand(10, 4), columns=['p', 'q', 'r', 's'])
df.plot(kind='area');

#To create an unstacked Area plot


Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

df.plot(kind='area', stacked=False);

#Bubble Chart
df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='scatter', x='a', y='b', s=df['c']*400);

#Hexagon Bin Plot


df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df['b'] = df['b'] + np.arange(1000)
df.plot(kind='hexbin', x='a', y='b', gridsize=25)

#3D Plot of a Surface


from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

#Let's adjust the view using the view_int. The following is the view at 0 elevation and 0 degree angle.
fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(elev=0., azim=0)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

#The following is the view at 50 elevation.


fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(elev=50., azim=0)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

#The following is the view at 50 elevation and 30 degrees angle.


fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(elev=50., azim=30)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

#Seaborn
Import seaborn as sns
#Distribution Plot
# Selecting style as white,
Dosen Pengampu: Dr. Kurnianingsih, S.T., M.T.

# dark, whitegrid, darkgrid


# or ticks
sns.set(style="white")
# Generate a random univariate
# dataset
rs = np.random.RandomState(10)
d = rs.normal(size=100)
# Plot a simple histogram and kde
# with binsize determined automatically
sns.distplot(d, kde=True, color="m")

# Line Plot
sns.set(style="dark")
fmri = sns.load_dataset("fmri")
# Plot the responses for different\
# events and regions
sns.lineplot(x="timepoint",
y="signal",
hue="region",
style="event",
data=fmri)

Anda mungkin juga menyukai