1 Data Science Introduction

filename: 01-introduction-to-plotly-real-gdp.Rmd

After completing this course, you will learn:
* How to define objects in R.
* How to use R functions.
* How to use plotly package as a beginner.
* The Plot.ly platform.

Clear the environment

rm(list=ls())

1.1 Import Data

Import text file data

data.vis.1.sa<-read.csv("./_data/data.vis.1.sa.csv")

./ represents the current working directory, normally where your .Rproj file is.
./_data/ represents the subdirectory under ’./`.

Check the first few lines

head(data.vis.1.sa)

Look at the class of each variable.

1.2 Convert to Date class

data.vis.1.sa$date <- as.Date(data.vis.1.sa$date)
head(data.vis.1.sa)

Look at the class of date variable.

1.3 Introduction to plotly

1.3.1 Install the package

You only need to install it once.

install.packages("plotly")

1.3.2 Load plotly package

Need to do it everytime you want to use plotly.

library(plotly)

1.4 Initiate a plotly plot

library(dplyr)
data.vis.1.sa %>% plot_ly(x=~date) %>%
  add_lines(y=~GDP,
            name="GDP") -> p0
p0
p0 %>% add_lines(y=~C,
          name="Consumption") -> p0
p0

The entire procedure is the same as:

data.vis.1.sa %>% plot_ly(x=~date) %>%
  add_lines(y=~GDP,
            name="GDP") %>%
  add_lines(y=~C,
            name="Consumption") -> p0
p0

Let’s plot all variables together.

data.vis.1.sa %>% plot_ly(x=~date) %>%
  add_lines(y=~GDP,
            name="GDP") %>%
  add_lines(y=~C,
            name="Consumption") %>%
  add_lines(y=~G,
            name="Gov't Purchase") %>%
  add_lines(y=~I,
            name="Investment") %>%
  add_lines(y=~Ex,
            name="Export") %>%
  add_lines(y=~Im,
            name="Import")-> p0
p0
1.4.0.0.1 1.4 Upload to plotly and modify in Plot.ly platform

Reference: Initialization for online ploting

Find your authentication API keys in your online settings. Save the following commands in your .Rprofile file (under your project directory) to be run every time you start R.

Sys.setenv("plotly_username"="各位的plotly平台使用者名稱")
Sys.setenv("plotly_api_key"="各位的API key的那一串英文與數字")
api_create(p0,filename="taiwan real gdp SA",fileopt="new")

In Plot.ly, you can
- adjust your graph by clicking edit
- download graph code by clicking view

1.5 Data visualization rule

Make sure you include the following components:
- Proper title(適當的標題)
- Unit of account (單位說明)
- Reference point: Chained dallors year, here. (參考基準點)
- Data source(資料來源)

1.6 Plot.ly trick

You can download your designed layout from plot.ly to use in your program.

p0 %>% layout(

  Copy and paste the code chunck XXX from the part inside list()
of layout<-list(XXX)

)