2016年8月25日

載入套件

  • 大括號 { } 裡面的 r 是告訴 RStudio 這邊是我要執行的 code
  • 緊接在 r 後面,不用逗號分隔開的,是這段程式碼(chunk)的名稱
library(plotly)
## Warning: package 'plotly' was built under R version 3.2.5
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 3.2.4
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:graphics':
## 
##     layout

Including Plots

  • 可以看到光是執行 library(plotly) 這行程式碼,就跳出一大堆系統訊息
  • 所以可以在 { } 寫入指令 message=FALSE 將系統訊息關閉
library(magrittr)

匯出精美的圖表

set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
d
## Source: local data frame [1,000 x 10]
## 
##    carat       cut  color clarity depth table price     x     y     z
##    (dbl)    (fctr) (fctr)  (fctr) (dbl) (dbl) (int) (dbl) (dbl) (dbl)
## 1   1.01 Very Good      D     SI1  62.1    59  6630  6.37  6.41  3.97
## 2   0.90     Ideal      D     SI1  62.4    55  5656  6.15  6.19  3.85
## 3   0.30     Ideal      D     SI1  61.6    56   709  4.34  4.30  2.66
## 4   0.30 Very Good      G     VS1  62.0    60   565  4.27  4.31  2.66
## 5   2.06   Premium      I     SI2  61.0    61 13912  8.18  8.10  5.02
## 6   1.56 Very Good      G    VVS1  59.7    59 15334  7.48  7.57  4.49
## 7   0.51   Premium      E     SI1  61.8    58  1443  5.15  5.11  3.17
## 8   1.16 Very Good      E     VS2  62.1    58  8520  6.63  6.70  4.14
## 9   0.32   Premium      E     VS2  61.2    59   702  4.40  4.43  2.70
## 10  1.08     Ideal      G     SI2  61.9    57  4544  6.55  6.57  4.06
## ..   ...       ...    ...     ...   ...   ...   ...   ...   ...   ...
plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
        mode = "markers", color = carat, size = carat)
### several box plots
plot_ly(ggplot2::diamonds, y = price, color = cut, type = "box")
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)

# specify map projection/options
g <- list(
  showframe = FALSE,
  showcoastlines = FALSE,
  projection = list(type = 'Mercator')
)

plot_ly(df, z = GDP..BILLIONS., text = COUNTRY, locations = CODE, type = 'choropleth',
        color = GDP..BILLIONS., colors = 'Blues', marker = list(line = l),
        colorbar = list(tickprefix = '$', title = 'GDP Billions US$')) %>%
  layout(title = '2014 Global GDP<br>Source:<a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">CIA World Factbook</a>',
         geo = g)