# Chart Studio 教學 {%hackmd @themes/orangeheart %} ###### tags: `R Language` [Chart Studio](https://chart-studio.plotly.com/feed/#/) 是一套可以提供使用者在遠端編輯程式碼、進行繪圖後,得到內嵌碼(embed code)的一個平台。該平台使用的繪圖套件是`plotly`,關於繪圖內容的教學請參考[Plotly R Open Source Graphing Library](https://plotly.com/r/) ## 在繪圖之前... 首先我們要安裝相關的套件: ```r install.packages("plotly") install.packages("ggplot2") ``` 安裝完套件後,我們便可以透過`library()`引用套件。 ```r library("plotly") library("ggplot2") ## Loading required package: ggplot2 ## ## Attaching package: 'plotly' ## The following object is masked from 'package:ggplot2': ## ## last_plot ## The following object is masked from 'package:stats': ## ## filter ## The following object is masked from 'package:graphics': ## ## layout ``` ## 登入 Chart Studio 因為我們要透過遠端的方式在 Chart Studio 放置我們的圖片,所以我們必須先擁有 Chart Studio 的帳號。申請完帳號之後,我們可以在 RStudio 中輸入以下指令,遠端登入 Chart Studio。 ```r Sys.setenv("plotly_username" = "你的帳號") Sys.setenv("plotly_api_key" = "API KEYS") ``` `API KEY` 可以透過以下方式獲取: **Account $\rightarrow$ Settings $\rightarrow$ API Keys $\rightarrow$ Enter Your Password $\rightarrow$ Get an one-time API keys**。接著我們可以從`github`安裝`ploty.R`。 ```r devtools::install_github("plotly/plotly.R") ## Skipping install of 'plotly' from a github remote, the SHA1 (32567a06) has not changed since last install. ## Use `force = TRUE` to force installation ``` ## 實踐:人均GDP與預期壽命 這邊我們使用`gapminder`套件。 ```r install.packages("gapminder") ``` 安裝完畢後,我們用`head()`查看`gapminder`的資料內容。 ```r library(gapminder) head(gapminder) ## # A tibble: 6 × 6 ## country continent year lifeExp pop gdpPercap ## <fct> <fct> <int> <dbl> <int> <dbl> ## 1 Afghanistan Asia 1952 28.8 8425333 779. ## 2 Afghanistan Asia 1957 30.3 9240934 821. ## 3 Afghanistan Asia 1962 32.0 10267083 853. ## 4 Afghanistan Asia 1967 34.0 11537966 836. ## 5 Afghanistan Asia 1972 36.1 13079460 740. ## 6 Afghanistan Asia 1977 38.4 14880372 786. ``` 假設我們對於人均 GDP 與預期壽命之間的相關性有興趣,我們可以透過散佈圖(scatter plot)呈現兩者的關係: ```r p <- gapminder %>% filter(year==1977) %>% ggplot(aes(gdpPercap, lifeExp, size = pop, color=continent)) + geom_point() + theme_bw() ``` 接著輸入`p`就可以在 RStudio 查看我們已經繪製的互動圖。接著我們可以上傳剛剛繪製的圖到 Chart Studio。 ```r api_create(p, filename='gdp') ``` <iframe width="900" height="800" frameborder="0" scrolling="no" src="//plotly.com/~xiaolong70701/33.embed"></iframe> 接著就可以進入到以下頁面,在右下角找到`</>`的圖示,便可以得到能夠`HTML`的內嵌碼。 ![](https://i.imgur.com/hxHKcap.gif)