Chart Studio 教學

tags: R Language

Chart Studio 是一套可以提供使用者在遠端編輯程式碼、進行繪圖後,得到內嵌碼(embed code)的一個平台。該平台使用的繪圖套件是plotly,關於繪圖內容的教學請參考Plotly R Open Source Graphing Library

在繪圖之前

首先我們要安裝相關的套件:

install.packages("plotly")
install.packages("ggplot2")

安裝完套件後,我們便可以透過library()引用套件。

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。

Sys.setenv("plotly_username" = "你的帳號")
Sys.setenv("plotly_api_key" = "API KEYS")

API KEY 可以透過以下方式獲取: Account

Settings
API Keys
Enter Your Password
Get an one-time API keys
。接著我們可以從github安裝ploty.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套件。

install.packages("gapminder")

安裝完畢後,我們用head()查看gapminder的資料內容。

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)呈現兩者的關係:

p <- gapminder %>%
  filter(year==1977) %>%
  ggplot(aes(gdpPercap, lifeExp, size = pop, color=continent)) +
  geom_point() +
  theme_bw()

接著輸入p就可以在 RStudio 查看我們已經繪製的互動圖。接著我們可以上傳剛剛繪製的圖到 Chart Studio。

api_create(p, filename='gdp')

接著就可以進入到以下頁面,在右下角找到</>的圖示,便可以得到能夠HTML的內嵌碼。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →