plotly

Plotly,一个用于做分析和可视化的在线平台,曾被网友称为“有史以来最牛逼”可视化神器(具体无从考据,只是在搜索资料时看到的),为何有如此称号?因为它功能强大。

其功能强大到不仅与多个主流绘图软件的对接,而且还可以像Excel那样实现交互式制图,而且图表种类齐全,并可以实现在线分享以及开源,等等;

本课程会帮助大家掌握这样一门技能,在自己日常的学习工作中,能够快速的,优雅的对数据进行交互式的可视化。

本课程的内容大纲如下:

  1. 简介与准备
  2. 绘制基本的图表
  3. 绘制统计图表
  4. 绘制科学图表
  5. 绘制金融图表
  6. 绘制3D图表
  7. 绘制动画
  8. 图形的细节调整

1准备

准备工作很简单,准备好Rstudio,然后使用以下代码进行安装:

install.packages("plotly")

然后我们就可以开始了

2. 绘制基本图形

基本图表包括了很多内容,分别罗列如下:

  1. 散点图
  2. 气泡图
  3. 线图
  4. 填充图
  5. 条形图
  6. 并图
  7. 桑基图

2.1 散点图

使用的数据是

library(plotly)

p <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
p

散点图可以修改的三个参数颜色,形状,现在来修改以下

p <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length,color = ~Species ,symbol =  ~Species)
p
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

2.2 气泡图

使用的数据是mtcars,气泡图是用多一维的数据来表示点的大小

p <- plot_ly(data = mtcars, x = ~mpg, y = ~wt,size = ~vs)
p
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
## Warning: `line.width` does not currently support multiple values.

修改一下颜色

p <- plot_ly(data = mtcars, x = ~mpg, y = ~wt,size = ~vs,color = ~am)
p
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
## Warning: `line.width` does not currently support multiple values.

2.3 线图

p <- plot_ly(data = mtcars, x = ~mpg, y = ~cyl,type = "scatter",mode = 'lines')
p

添加不同的颜色

p <- plot_ly(data = mtcars, x = ~mpg, y = ~cyl,type = "scatter",mode = 'lines',color = ~am)
p
## Warning: line.color doesn't (yet) support data arrays

## Warning: line.color doesn't (yet) support data arrays

2.4 填充图形

绘制填充图关键的参数是fill,在第二条曲线的调用中,将内部填充设置fill为区域图“tozeroy”。有关fill选项结帐的更多信息和选项,请访问https://plot.ly/r/reference/#scatter-fill

density <- density(diamonds$carat)

p <- plot_ly(x = ~density$x, y = ~density$y, type = 'scatter', mode = 'lines', fill = 'toself') # tozeroy tozerox
p

绘制两条填充曲线

diamonds1 <- diamonds[which(diamonds$cut == "Fair"),]
density1 <- density(diamonds1$carat)

diamonds2 <- diamonds[which(diamonds$cut == "Ideal"),]
density2 <- density(diamonds2$carat)

p <- plot_ly(x = ~density1$x, y = ~density1$y, type = 'scatter', mode = 'lines', name = 'Fair cut', fill = 'tozeroy') %>%
  add_trace(x = ~density2$x, y = ~density2$y, name = 'Ideal cut', fill = 'tozeroy')
p

2.5 条形图

基本的条形图绘制,将type参数设置为bar

p <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar"
)

p

分组条形图

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

p <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
  add_trace(y = ~LA_Zoo, name = 'LA Zoo') 

p

2.6 饼图

p <- plot_ly(iris, labels = ~Species, values = ~Sepal.Length, type = 'pie')
p

甜甜圈图

require(tidyverse)
## Loading required package: tidyverse
## ─ Attaching packages ────────────────────────── tidyverse 1.2.1 ─
## ✔ tibble  2.0.0     ✔ purrr   0.2.5
## ✔ tidyr   0.8.2     ✔ dplyr   0.7.8
## ✔ readr   1.3.1     ✔ stringr 1.3.1
## ✔ tibble  2.0.0     ✔ forcats 0.3.0
## Warning: package 'tidyr' was built under R version 3.4.4
## Warning: package 'readr' was built under R version 3.4.4
## Warning: package 'purrr' was built under R version 3.4.4
## Warning: package 'dplyr' was built under R version 3.4.4
## Warning: package 'stringr' was built under R version 3.4.4
## ─ Conflicts ─────────────────────────── tidyverse_conflicts() ─
## ✖ dplyr::filter() masks plotly::filter(), stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)

p <- mtcars %>%
  group_by(manuf) %>%
  summarize(count = n()) %>%
  plot_ly(labels = ~manuf, values = ~count) %>%
  add_pie(hole = 0.6)

2.7 桑基图

library(plotly)
library(rjson)
## Warning: package 'rjson' was built under R version 3.4.4
json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy_dark.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

p <- plot_ly(
  type = "sankey",

  orientation = "h",
  
  node = list(
    label = json_data$data[[1]]$node$label
    
  ),
  
  link = list(
    source = json_data$data[[1]]$link$source,
    target = json_data$data[[1]]$link$target,
    value =  json_data$data[[1]]$link$value
  )
)

p

我们来看一下具体是如何实现:首先 type = “sankey” 制定了绘制的是sankey,桑基图。然后orientation=’h’表明的是绘制出的图形是横向的。node 参数指定了绘制图形的节点。link里面参数制定了绘制节点的流向以及流量的大小。

我们自己来构造数据,来实现一个自己的例子:

图形的节点选取为字母表的前六个,然后设置了7个连接,分别为:(0,1),(1,2),(2,3),(3,4),c(0,2),c(0,3),c(0,4).每个连接的流量为:sample(c(1,2,3,4,5,6,7))

p <- plot_ly(
  type = "sankey",
  
  orientation = "h",
  
  node = list(
    label = letters[1:5]
    
  ),
  
  link = list(
    source = c(0,1,2,3,0,0,0),
    target = c(1,2,3,4,2,3,4),
  value =  sample(c(1,2,3,4,5,6,7))
)
) 
p

3. 统计图表

统计图表包括

  1. 误差棒
  2. 方块图
  3. 直方图
  4. 2d直方图
  5. 二维直方轮廓图
  6. 小提琴图
  7. Splom图

3.1 绘制误差棒图

误差棒图本质上是带有误差线的条形图

library(plyr)
## -------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## -------------------------------------------------------------------------
## 
## Attaching package: 'plyr'
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## The following object is masked from 'package:purrr':
## 
##     compact
## The following objects are masked from 'package:plotly':
## 
##     arrange, mutate, rename, summarise
data_mean <- ddply(ToothGrowth, c("supp", "dose"), summarise, length = mean(len))
data_sd <- ddply(ToothGrowth, c("supp", "dose"), summarise, length = sd(len))
data <- data.frame(data_mean, data_sd$length)
data <- rename(data, c("data_sd.length" = "sd"))
data$dose <- as.factor(data$dose)


p <- plot_ly(data = data[which(data$supp == 'OJ'),], x = ~dose, y = ~length, type = 'bar',
             error_y = ~list(array = sd,
                             color = '#000000')) %>% 
   add_trace(data = data[which(data$supp == 'VC'),], name = 'VC')

p

绘制带有误差棒的散点图

p <- plot_ly(data = data[which(data$supp == 'OJ'),], x = ~dose, y = ~length, type = 'scatter', mode = 'markers',
        name = 'OJ',
        error_y = ~list(array = sd,
                        color = '#000000')) %>%
  add_trace(data = data[which(data$supp == 'VC'),], name = 'VC')
p

3.2 箱线图

箱线图的基本绘制方式

p <- plot_ly(y = ~rnorm(50), type = "box") %>%
  add_trace(y = ~rnorm(50, 1))
p

添加抖动点

p <- plot_ly(y = ~rnorm(50), type = "box", boxpoints = "all", jitter = 0.3,
        pointpos = -1.8)
p

添加多个箱线图

p <- plot_ly(ggplot2::diamonds, y = ~price, color = ~cut, type = "box")
p

3.3 直方图

绘制基本的直方图

library(plotly)
p <- plot_ly(x = ~rnorm(50), type = "histogram")

p

归一化直方图

p <- plot_ly(x = ~rnorm(50),
             type = "histogram",
             histnorm = "probability")

p

叠加直方图

p <- plot_ly(alpha = 0.6) %>%
  add_histogram(x = ~rnorm(500)) %>%
  add_histogram(x = ~rnorm(500) + 1) %>%
  layout(barmode = "overlay")
p

3.4 2D直方图

首先,我们构造一个二维正态分布的数据:

# 构造二维正太分布
s <- matrix(c(1, -.75, -.75, 1), ncol = 2)
obs <- mvtnorm::rmvnorm(500, sigma = s)

#  绘制一维的直方图
plot_ly(x = ~obs[,1], type = "histogram")
p <- plot_ly(x = obs[,1], y = obs[,2])
p
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
# 这个时候是默认散点图的
pp <- subplot(
  p %>% add_markers(alpha = 0.2),
  p %>% add_histogram2d()
)
pp

3.5 二维轮廓直方图

二维轮廓直方图的基本绘制:

s <- matrix(c(1, -.75, -.75, 1), ncol = 2)
obs <- mvtnorm::rmvnorm(500, sigma = s)

p <- plot_ly(x = obs[,1], y = obs[,2]) %>% 
  add_trace(type='histogram2dcontour')

2D直方图轮廓子图

x <- rnorm(1000)
y <- rnorm(1000)
s <- subplot(
  plot_ly(x = x, color = I("black"), type = 'histogram'), 
  plotly_empty(), 
  plot_ly(x = x, y = y, type = 'histogram2dcontour', showscale = F), 
  plot_ly(y = y, color = I("black"), type = 'histogram'),
  nrows = 2, heights = c(0.2, 0.8), widths = c(0.8, 0.2), 
  shareX = TRUE, shareY = TRUE, titleX = FALSE, titleY = FALSE
)
## Warning: No trace type specified and no positional attributes specified
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
s

3.6 小提琴图

library(plotly)
p <- plot_ly(x = ~rnorm(50), type = "violin",box = list(
      visible = T
    ),meanline = list(
      visible = T
    ))
p

分组的小提琴图

p <- plot_ly(data = iris,x = ~Petal.Width,color = ~Species, type = "violin",box = list(
      visible = T
    ),meanline = list(
      visible = T
    ))
p

4. 科学图表

  1. 雷达图
  2. 热图

4.1 雷达图

基本的雷达图

p <- plot_ly(
  
    type = 'scatterpolar',
    r = c(39, 28, 8, 7, 28, 39),
    theta = c('A','B','C', 'D', 'E', 'A'),
    fill = 'toself'
  )
p
## No scatterpolar mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

多轨迹的雷达图

p <- plot_ly(
    type = 'scatterpolar',
    fill = 'toself'
  ) %>%
  add_trace(
    r = c(39, 28, 8, 7, 28, 39),
    theta = c('A','B','C', 'D', 'E', 'A'),
    name = 'Group A'
  ) %>%
  add_trace(
    r = c(1.5, 10, 39, 31, 15, 1.5),
    theta = c('A','B','C', 'D', 'E', 'A'),
    name = 'Group B'
  )
p
## No scatterpolar mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
## No scatterpolar mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
## No scatterpolar mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

4.2 热图

基本热图

p <- plot_ly(z = volcano, type = "heatmap")
p

设置颜色

p <- plot_ly(z = volcano, colors = "Greys", type = "heatmap")
p

想要知道有哪些颜色可以选择,可以(参见RColorBrewer::brewer.pal.info有效名称)

5. 金融图表

  1. 时间序列图
  2. 蜡烛图
  3. OHLC图

5.1 时间序列

today <- Sys.Date()
tm <- seq(0, 600, by = 10) # 生成600天的数据
x <- today - tm
y <- rnorm(length(x))
p <- plot_ly(x = ~x, y = ~y, mode = 'lines', text = paste(tm, "days from today"))
p
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter

带有时区的时间序列

now_lt <- as.POSIXlt(Sys.time(), tz = "GMT")
tm <- seq(0, 600, by = 10)
x <- now_lt - tm
y <- rnorm(length(x))
p <- plot_ly(x = ~x, y = ~y, mode = 'lines', text = paste(tm, "seconds from now in GMT"))

p
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter

5.2 蜡烛图

绘制蜡烛图首先要使用quantmod绘制

library(quantmod)
## Warning: package 'quantmod' was built under R version 3.4.4
## Loading required package: xts
## Warning: package 'xts' was built under R version 3.4.4
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 3.4.4
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 3.4.4
## Version 0.4-0 included new data defaults. See ?getSymbols.
getSymbols("AAPL",src='yahoo')
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## 
## WARNING: There have been significant changes to Yahoo Finance data.
## Please see the Warning section of '?getSymbols.yahoo' for details.
## 
## This message is shown once per session and may be disabled by setting
## options("getSymbols.yahoo.warning"=FALSE).
## [1] "AAPL"
# basic example of ohlc charts
df <- data.frame(Date=index(AAPL),coredata(AAPL))
df <- tail(df, 30)

p <- df %>%
  plot_ly(x = ~Date, type="candlestick",
          open = ~AAPL.Open, close = ~AAPL.Close,
          high = ~AAPL.High, low = ~AAPL.Low)

p

6. 3D图

  1. 3D散点图
  2. 3D线图

6.1 3D散点图

mtcars$am[which(mtcars$am == 0)] <- 'Automatic'
mtcars$am[which(mtcars$am == 1)] <- 'Manual'
mtcars$am <- as.factor(mtcars$am)

p <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, color = ~am, colors = c('#BF382A', '#0C4B8E'))
p
## No trace type specified:
##   Based on info supplied, a 'scatter3d' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
## No scatter3d mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

绘制3D泡泡图

mtcars$am[which(mtcars$am == 0)] <- 'Automatic'
mtcars$am[which(mtcars$am == 1)] <- 'Manual'
mtcars$am <- as.factor(mtcars$am)

p <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec,size =  ~disp, color = ~am, colors = c('#BF382A', '#0C4B8E'))
p
## No trace type specified:
##   Based on info supplied, a 'scatter3d' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
## No scatter3d mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

6.2 3D线图

p <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec,type = "scatter3d",mode = 'lines')
p

3D随机游走图

data <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/_3d-line-plot.csv')

p <- plot_ly(data, x = ~x1, y = ~y1, z = ~z1, type = 'scatter3d', mode = 'lines',
        line = list(color = '#1f77b4', width = 1)) %>%
  add_trace(x = ~x2, y = ~y2, z = ~z2,
            line = list(color = 'rgb(44, 160, 44)', width = 1)) %>%
  add_trace(x = ~x3, y = ~y3, z = ~z3,
            line = list(color = 'bcbd22', width = 1))
p

7. 绘制动画图

原理就是,frames指向一个数字列表,每个数字都会在实例化时进行循环

df <- data.frame(
  x = c(1,2,1), 
  y = c(1,2,1), 
  f = c(1,2,3)
)

p <- df %>%
  plot_ly(
    x = ~x,
    y = ~y,
    frame = ~f,
    type = 'scatter',
    mode = 'markers',
    showlegend = F
  )
p

更加复杂的一个例子:

library(gapminder)

p <- gapminder %>%
  plot_ly(
    x = ~gdpPercap, 
    y = ~lifeExp, 
    size = ~pop, 
    color = ~continent, 
    frame = ~year, 
    text = ~country, 
    hoverinfo = "text",
    type = 'scatter',
    mode = 'markers'
  ) %>%
  layout(
    xaxis = list(
      type = "log"
    )
  )

p

我们来分析一下这个图

8. 细节调整

接下来我们来介绍一些绘制图形的一些细节调整,这些调整方式大多是通用的,因此,放在本课程的最后一个部分进行讲解

使用到的数据集是mycars数据集合,首先绘制一个散点图:

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter")
p
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

这里显示需要设置mode,mode有三个参数可以选: “lines”, “markers”, “text” ,也可以设置类似于这样“lines + markers”

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers")
p

改变颜色

将颜色设置成为红色

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",color = I("red"))
p

通过marker参数设置颜色和其他选项

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",marker = list(color = 'green',size = 10))
p

添加line参数

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",marker = list(color = 'green',size = 10,line = list(color = "blue",width = 10)))
p

利用连续变量和离散变量设置颜色

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",color = ~as.factor(cyl))
p
p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",color = ~as.factor(cyl),colors = "Set1")
p

定义自己想要的颜色,这里设置了三种颜色,红,蓝,绿

pal <- c("red","blue","green")

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",color = ~as.factor(cyl),colors = pal)
p

通过symbol参数,改变散点图形状

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",symbol = ~as.factor(cyl))
p

通过symbol参数,指定散点图的形状

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",symbol = ~as.factor(cyl),symbols = c("circle","x","o"))
p

通过连续变量设置颜色

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",color = ~disp)
p

同时设置颜色和大小,颜色是因子,大小是连续

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",color = ~as.factor(cyl),size = ~disp)
p
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

图例的调整

是否显示图例

p %>% layout(showlegend = TRUE)
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.
p %>% layout(showlegend = FALSE)
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

图例按照什么方向摆放

p %>% layout(legend = list(orientation = "h"))
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.
p %>% layout(legend = list(orientation = "v"))
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

图例放在整个图形的什么位置

p %>% layout(legend = list(x = 0.1, y= 0.1))
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

最标轴的调整,添加标题,x,y轴的名字

p %>% layout(legend = list(x = 0.1, y= 0.1),title = "Plot",xaxis = list(title = "weigth"),yaxis = list(title = "MPG"))
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

是否显示坐标轴

p %>% layout(legend = list(x = 0.1, y= 0.1),title = "Plot",xaxis = list(title = "weigth",showgrid = FALSE),yaxis = list(title = "MPG"))
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

修改交互文本,text参数来修改交互式文本

p <- plot_ly(data = mtcars,x = ~wt,y = ~mpg,type = "scatter",mode = "markers",hoverinfo = "text",text = paste("Miles per gallon:",mtcars$wt,"<br>","Weigth:",mtcars$mpg))
p

hoverinfo 是什么含义,指定的是如何显示交互文本

add_annotations()介绍,这个函数可以在途中添加数据

在这里标识除了wt最小的值的那个点

p <- plot_ly(data = mtcars,x = ~wt,y=~mpg)
p %>% add_annotations(x = mtcars$wt[which.min(mtcars$wt)],
                      y = mtcars$mpg[which.min(mtcars$wt)],
                      text = "good milege")
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

这里标示出wt最大的那个点

p %>% add_annotations(y = mtcars$mpg[which.max(mtcars$wt)],
                      x = mtcars$wt[which.max(mtcars$wt)],
                      text = "good milege",showarrow = FALSE)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

标识多个点

plot_ly(data = mtcars,x=~mpg,y=~wt,type = "scatter",mode = 'markers') %>% add_annotations(x= mtcars$mpg[mtcars$am==0],text = "point")