阅读 173

plotly for R

简介

  • 交互式绘图工具, 提供python, R, js接口, 以R接口为例

  • api类似, 需要注意在参数中涉及子项的在R中使用列表, 在python中使用字典

  • 支持管道符操作 %>%, 类似ggplot2的 +

  • 详细教程参见 (https://plotly.com/r/)

基本命令

  • 基本绘图命令:plot_ly(data, x, y, z, type, mode...)

x: x轴数据
y: y轴数据
z: z轴数据 (三维图形)
text: 文本内容
type: 图形的类型, 包括点图, 柱状图, 热图等
name: 名称, 在图注中使用
alpha: 透明度0-1, 0表示透明, 1表示不透明
size/sizes: 点的大小可以指定变量(~size), 也可以使用区间表示c(10, 100)
linetype/linetypes: 线的类型
color/colors: 图形的颜色, 可选择变量或预设的颜色集合
symbol/symbols: 指定形状, 例如symbol = ~symbol_indicessymbols = c('circle','x','o')
stroke/strokes: 边框的颜色
width/height: 图形的宽高
showlegend: 布尔值, 当前trace是否显示图例

图形命令 (add_trace/add_xxx)

点类型 (散点图, 折线图, 气泡图...)

散点图

  • 指定参数add_trace(..., type="scatter", mode="")

  • 等同于add_markers/add_lines

  • marker: 指定标记点的相关特征, 包括边框, 颜色, 大小等

symbol: 指定点的形状
color: 点的颜色
colorscale: 设置色阶, colorscale必须是一个数组, 设置0 ~ 1中某个区间想要使用的颜色, 至少需要最低(0)和最高(1)值的映射。例如: list(c(0.0, '#19d3f3'), c(0.333, '#e763fa'), c(0.666, '#e763fa'), c(1, '#636efa'))。(左闭右开的区间)
opacity: 点的透明度(0-1)
size: 点的大小, 默认6
line: 传入列表, 指定点的边框特征

width: 边框的粗细
color: 边框的颜色
colorscale: 指定色阶

  • line: 传入列表, 指定线的特征

color: 线的颜色
width: 线的粗细 (Default: 2)
shape: 线的形状, 可选参数有: "linear"(直线) | "spline"(平滑曲线) | "hv"(阶梯曲线) | "vh" | "hvh" | "vhv"
smoothing: 平滑度(0-1.3), 默认1
simplify: 通过删除几乎共线的点来简化直线
dash: 设置线条的虚线样式: "solid" | "dot" | "dash" | "longdash" | "dashdot" | "longdashdot"

  • connectgaps: 应用于折线图的参数, 确定所提供的数据数组中的间隙(NA)是否连接。

  • 同属scatter类型下的不同模式 (mode)

scatter类型x与y是一一对应的, 又有三种模式, 可以绘制散点图或折线图

  • mode="markers": 绘制点图, 等同于 add_markers

  • mode="lines": 绘制线图, 等同于 add_lines

  • mode="lines+markers": 散点图和折线图的结合

library(plotly)plot_ly(economics, x = ~date, y = ~uempmed) %>% 
  add_trace(type="scatter", mode="markers", marker = list(color = "black", line = list(color = "red", width = 1)))## head(economics)## # A tibble: 6 x 6##   date         pce    pop psavert uempmed unemploy
##   <date>     <dbl>  <dbl>   <dbl>   <dbl>    <dbl>## 1 1967-07-01  507. 198712    12.6     4.5     2944## 2 1967-08-01  510. 198911    12.6     4.7     2945## 3 1967-09-01  516. 199113    11.9     4.6     2958## 4 1967-10-01  512. 199311    12.9     4.9     3143## 5 1967-11-01  517. 199498    12.8     4.7     3066## 6 1967-12-01  525. 199657    11.8     4.8     3018## 等同于以下命令plot_ly(economics, x = ~date, y = ~uempmed) %>% 
  add_markers(marker = list(color = "black", line = list(color = "red", width = 1)))


Markers


在散点图上又有许多扩展, 将点连成线就变成了折线图


plot_ly(economics, x = ~date, y = ~uempmed) %>% 
  add_trace(type = "scatter", mode = "lines", 
            line = list(color = "green", width = 2))

## 等同于以下命令
plot_ly(economics, x = ~date, y = ~uempmed) %>% 
  add_trace(type = "scatter", mode = "lines", 
            line = list(color = "green", width = 2))

Lines

也可以在折线图的基础上将点标记出来

  • 包含的trace: marker, line

plot_ly(economics, x = ~date, y = ~uempmed) %>% 
  add_trace(type = "scatter", mode = "markers+lines", 
            marker = list(color = "black", line = list(color = "red", width = 1)),
            line = list(color = "green", width = 2))## 等同于以下命令plot_ly(economics, x = ~date, y = ~uempmed) %>% 
  add_trace(type = "scatter", mode = "lines", 
            line = list(color = "green", width = 2)) %>% 
  add_trace(type = "scatter", mode = "markers",
            marker = list(color = "black", line = list(color = "red", width = 1)))

Markers+Lines

气泡图则是将点的大小和颜色与其他特征联系起来 (Bubble)

library(plotly)data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")data$State <- as.factor(c('Massachusetts', 'California', 'Massachusetts', 'Pennsylvania', 'New Jersey', 'Illinois', 'Washington DC',
                          'Massachusetts', 'Connecticut', 'New York', 'North Carolina', 'New Hampshire', 'New York', 'Indiana',
                          'New York', 'Michigan', 'Rhode Island', 'California', 'Georgia', 'California', 'California'))## head(data)##      School Women Men Gap         State## 1       MIT    94 152  58 Massachusetts## 2  Stanford    96 151  55    California## 3   Harvard   112 165  53 Massachusetts## 4    U.Penn    92 141  49  Pennsylvania## 5 Princeton    90 137  47    New Jersey## 6   Chicago    78 118  40      Illinoisfig <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', 
               mode = 'markers', size = ~Gap, color = ~State, colors = 'Paired',
               marker = list(opacity = 0.5, sizemode = 'diameter', line = list(color="white", width=1)))fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
                      xaxis = list(showgrid = FALSE),
                      yaxis = list(showgrid = FALSE),
                      showlegend = FALSE)fig


Bubble


哑铃图, 将起始点与终止点用segment连接起来 (Dumbbell)


  • 包含的trace: marker, line

s <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")# order factor levels by men's income (plot_ly() will pick up on this ordering)s$School <- factor(s$School, levels = s$School[order(s$Men)])## head(s)##      School Women Men Gap## 1       MIT    94 152  58## 2  Stanford    96 151  55## 3   Harvard   112 165  53## 4    U.Penn    92 141  49## 5 Princeton    90 137  47## 6   Chicago    78 118  40library(plotly)fig <- plot_ly(s)## add_segment添加线段, 指定起始位置x, y和终止位置xend, yendfig <- fig %>% add_segments(x = ~Women, xend = ~Men, y = ~School, yend = ~School, showlegend = F,
                            line = list(color = "rgb(230,230,230)"))fig <- fig %>% add_markers(x = ~Women, y = ~School, name = "Women", color = I("pink"))fig <- fig %>% add_markers(x = ~Men, y = ~School, name = "Men", color = I("blue"))fig <- fig %>% layout(
  title = "Gender earnings disparity",
  xaxis = list(title = "Annual Salary (in thousands)"),
  margin = list(l = 65))fig

Dumbbell

对于多个变量, 创建二维散点图矩阵 (Splom)

  • opacity: 透明度, 0 ~ 1的区间 (Default: 1)

  • dimensions: 传入列表, 指定需要绘图的维度 (每一个维度都需要指定下面的参数, 用列表包裹起来)

visible: 布尔值, 是否可见
label: 设置与此splom维度对应的标签
values: 设置要绘制的值

  • marker: 设置splom中点的特征

color: 设置点的颜色
colorscale: 设置色阶
symbol: 设置点的形状
size: 设置点的大小
line: 传入列表, 设置点的边框信息

color: 设置边框的颜色
width: 设置边框的宽度

  • text: 文本信息

library(plotly)df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/iris-data.csv')## head(df)##   sepal.length sepal.width petal.length petal.width       class## 1          5.1         3.5          1.4         0.2 Iris-setosa
## 2          4.9         3.0          1.4         0.2 Iris-setosa
## 3          4.7         3.2          1.3         0.2 Iris-setosa
## 4          4.6         3.1          1.5         0.2 Iris-setosa
## 5          5.0         3.6          1.4         0.2 Iris-setosa
## 6          5.4         3.9          1.7         0.4 Iris-setosa

## 注意色阶是左闭右开的区间
pl_colorscale=list(c(0.0, '#19d3f3'),
                   c(0.333, '#e763fa'),
                   # c(0.333, '#e763fa'),
                   c(0.666, '#e763fa'),
                   # c(0.666, '#636efa'),
                   c(1, '#636efa'))axis = list(showline=FALSE,
            zeroline=FALSE,
            gridcolor='#ffff',
            ticklen=4)fig <- df %>%
  plot_ly() fig <- fig %>%
  add_trace(
    type = 'splom',
    dimensions = list(
      list(label='sepal length', values=~sepal.length),
      list(label='sepal width', values=~sepal.width),
      list(label='petal length', values=~petal.length),
      list(label='petal width', values=~petal.width)
    ),
    text=~class,
    marker = list(
      color = as.integer(as.factor(df$class)) / 3,
      colorscale = pl_colorscale,
      size = 7,
      line = list(
        width = 1,
        color = 'rgb(230,230,230)'
      )
    )
  ) fig <- fig %>%
  layout(
    title= 'Iris Data set',
    hovermode='closest',
    dragmode= 'select',
    plot_bgcolor='rgba(240,240,240, 0.95)',
    xaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
    yaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
    xaxis2=axis,
    xaxis3=axis,
    xaxis4=axis,
    yaxis2=axis,
    yaxis3=axis,
    yaxis4=axis  )fig

Splom

柱类型(柱状图, 堆积图, 直方图, 瀑布图...)

柱状图 (Bar Charts)

  • 指定参数add_trace(..., type="bar")

  • 等同于add_bars

  • marker参数指定柱子的特征, 包括边框, 颜色等

  • width参数如果指定变量则表示柱子的宽度

  • color参数支持使用I("颜色")指定颜色/rgb(0.0.0)指定rgb颜色/rgba(0.0.0.0)指定rgb颜色和透明度

  • orientation: 设置条的方向, 可选"v" (竖直) / "h" (水平)

  • marker: 传入列表, 指定柱子的特征, 包括颜色, 边框等

line: 传入列表, 指定边框的颜色, 粗细等特征
color: 指定柱子的颜色
opacity: 指定柱子的透明度

  • layout中对于柱状图的设置

barmode: 设置直方图的展示形式, 可选参数: "stack" (堆叠展示) | "group" (分组展示) | "overlay" (覆盖展示) | "relative" (相对高度) (Default: "group")
bargap: 每个柱子的间隔
barnorm: bar的标准化形式, 可选参数: "" | "fraction" (分数) | "percent" (百分数) (Default: "")
bargap: 设置相邻位置坐标 (不同特征) bar之间的间距 (0 ~ 1的区间)
bargroupgap: 设置相同坐标 (相同特征) bar之间的间距 (0 ~ 1的区间) (Default: 0)

library(plotly)## 构建数据x= c(1, 2, 3, 5.5, 10)y= c(10, 8, 6, 4, 2)width = c(0.8, 0.8, 0.8, 3.5, 4)data <- data.frame(x, y, width)## 绘图fig <- plot_ly(data)fig <- fig %>% add_trace(
  type="bar",
  x= ~x,
  y= ~y,
  width = ~width,
  marker = list(color = 'rgb(158,202,225)', 
                line = list(color = 'rgb(8,48,107)', width = 1.5)))fig

bar


直方图 (Histgram)

  • 指定参数add_trace(..., type="histogram")

  • 等同于 add_histogram

  • opacity: 柱子的透明度, 0 ~ 1的区间 (Default: 1)

  • histfunc: 每一个柱子的统计指标: "count" (默认) | "sum" | "avg" | "min" | "max"

  • histnorm: 指定用于此直方图规格化类型: "" (默认) | "percent" | "probability" | "density" | "probability density"

  • marker: 传入列表参数, 指定直方图中柱子的特征

color: 直方图的颜色
opacity: 直方图的透明度, 0 ~ 1的区间 (Default: 1)
line: 传入列表, 指定直方图的边框特征

width: 边框的粗细
color: 边框的颜色

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

fig

Overlayed Histgram


瀑布图 (Waterfall)

  • 指定参数add_trace(..., type="waterfall")

  • measure: 包含值类型的数组, 可选参数: "relative" (相对变化) | "total" (计算总和) | "absolute" (重置计算结果, 绝对变化)

library(plotly)x= list("Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax")measure= c("relative", "relative", "total", "relative", "relative", "total")text= c("+60", "+80", "", "-40", "-20", "Total")y= c(60, 80, 0, -40, -20, 0)data = data.frame(x=factor(x,levels=x),measure,text,y)fig <- plot_ly(
  data, name = "20", type = "waterfall", measure = ~measure,
  x = ~x, textposition = "outside", y= ~y, text =~text,
  connector = list(line = list(color= "rgb(63, 63, 63)"))) fig <- fig %>%
  layout(title = "Profit and loss statement 2018",
        xaxis = list(title = ""),
        yaxis = list(title = ""),
        autosize = TRUE,
        showlegend = TRUE)fig

Waterfall

数据整体分布 (箱线图, 小提琴图...)

箱线图 (Box Plot)

  • 包含的trace: marker(点)

  • 使用add_trace(..., type="box")绘制箱线图

  • 等同于add_boxplot

  • quartilemethod参数指定了箱线图的定量方法, 包括linear(默认)/inclusive/exclusive

  • boxpoints: 在箱线图的基础上绘制点图 "all" | "outliers" | FALSE

  • opacity: 箱线图的透明度, 0 ~ 1的范围 (Default: 1)

  • fillcolor: 箱线图的填充颜色

  • pointpos参数指定散点图与箱线图的偏移量, -2 ~ 2 的区间

  • jitter指定散点随即抖动的范围, 0 ~ 1的区间

  • notched: 布尔类型, 是否创建带凹槽的箱线图

  • line: 传入列表, 指定边框信息, 包括颜色

  • marker: 传入列表, 指定箱线图中点的特征

outliercolor: 异常点的颜色
symbol: 点的形状 (Default: "circle")
opacity: 点的透明度 (Default: 1)
color: 点的颜色(指定的jitter的颜色)
size: 点的大小, 大于0的范围 (Default: 6)
line : 传入列表参数, 指定点的边框信息

color: 边框的颜色 (Default: "#444")
width: 边框的粗细 (Default: 0)
outliercolor: 异常点的边框的颜色
outlierwidth: 异常点的边框的粗细 (Default: 1)

  • line: 传入列表, 指定箱线图的边框信息

color: 边框的颜色
width: 边框的宽度 (Default: 2)

  • boxmean: 展示箱线图均值所在的位置:  TRUE | "sd" (mean和sd都标记出来) | FALSE

  • layout中对于箱线图的参数

boxmode: 箱线图的展示形式, 可选参数: "group" (分组展示) | "overlay" (覆盖显示)
boxgap: 设置相邻位置坐标 (不同特征) box之间的间距 (0 ~ 1的区间) (Default: 0.3)
boxgroupgap: 设置相同坐标 (相同特征) box的间距 (0 ~ 1的区间) (Default: 0.3)

library(plotly)fig <- plot_ly(y = list(1,2,3,4,5), type = "box", quartilemethod="linear", name="Linear Quartile Mode") %>% 
  add_trace(y = list(1,2,3,4,5), quartilemethod="inclusive", name="Inclusive Quartile Mode") %>% 
  add_trace(y = list(1,2,3,4,5), quartilemethod="exclusive", name="Exclusive Quartile Mode") %>% 
  layout(title = "Modifying The Algorithm For Computing Quartiles")fig

Boxplot

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

fig

Boxplot+Jitter


小提琴图 (Violin Plot)

  • 包含的trace: box(小提琴中的箱线图), marker(点), line(边框)

  • 指定参数add_trace(..., type="voilin")绘制小提琴图

  • box: 传入列表参数, 控制小提琴中的箱线图特征

visable: 是否在小提琴中可见箱线图(T | F)
width: 箱线图的宽度(Default: 0.25)
fillcolor: 箱线图的填充颜色
line: 传入列表参数, 设定箱线图的边框特征

color: 箱线图的边框颜色
width: 箱线图的边框粗细

  • marker: 传入列表参数, 设定小提琴图中点的特征

outliercolor: 离群点的颜色 (只包含离群点)
symbol: 点的形状 (Default: "circle")
opacity: 点的透明度, 0-1的区间 (Default: 1)
size: 点的大小 (Default: 6)
line: 传入列表参数, 设置点的边框特征

color: 点的边框的颜色 (包含所有点)
width: 点的边框的粗细 (包含所有点)
outliercolor: 离群点的边框的颜色 (只包含离群点)
outlierwidth: 离群点的边框的粗细 (只包含离群点)

  • line: 传入列表参数, 指定小提琴的边框特征

color: 小提琴的边框颜色
width: 小提琴的边框粗细 (Default: 2)

  • side: 指定小提琴展示在哪一侧, 可选参数有: "negative"(左侧) | "positive"(右侧) | "both"(两侧, 默认)

  • points: 展示点, 可选参数有: "all"(全部点) | "outliers"(异常点, 默认) | FALSE(不展示点, 只展示小提琴)

  • pointpos: 散点图与小提琴图的偏移量,  -2 ~ 2的区间

  • jitter: 点的抖动范围, 0 ~ 1的范围

  • filecolor: 小提琴图的填充颜色

  • meanline: 传入列表小提琴内部显示与样本平均值相对应的线

visable: 线是否可见(TRUE | FALSE)
color: 线的颜色
width: 线的宽度

  • layout中对于小提琴图的设定 (官网没有这些参数, 但是对图形有影响)

violinmode: 小提琴图的展示形式, 可选参数: "group" (分组展示) | "overlay" (覆盖显示)
violingap: 设置相邻位置坐标 (不同特征) violin之间的间距 (0 ~ 1的区间) (Default: 0.3)
violingroupgap: 设置相同坐标 (相同特征) violin的间距 (0 ~ 1的区间) (Default: 0.3)

library(plotly)df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")fig <- df %>%
  plot_ly(type = 'violin') fig <- fig %>%
  add_trace(
    x = ~day[df$smoker == 'Yes'],
    y = ~total_bill[df$smoker == 'Yes'],
    legendgroup = 'Yes',
    scalegroup = 'Yes',
    name = 'Yes',
    side = 'negative',
    box = list(
      visible = T
    ),
    meanline = list(
      visible = T
    ),
    color = I("blue")
  ) fig <- fig %>%
  add_trace(
    x = ~day[df$smoker == 'No'],
    y = ~total_bill[df$smoker == 'No'],
    legendgroup = 'No',
    scalegroup = 'No',
    name = 'No',
    side = 'positive',
    box = list(
      visible = T
    ),
    meanline = list(
      visible = T
    ),
    color = I("green")
  ) fig <- fig %>%
  layout(
    xaxis = list(
      title = ""  
    ),
    yaxis = list(
      title = "",
      zeroline = F
    ),
    violingap = 0,
    violingroupgap = 0,
    violinmode = 'overlay'
  )fig

splited violin

不知道为何violingap, violingroupgap, violinmode会报warning提示没有该参数, 但是实际改变这些参数确实是对图形有影响的

桑基图 (Sankey Diagram)

  • 包含的trace: node (节点), link (连接)

  • 指定参数add_trace(..., type="sankey")

  • 节点node和连接link

  • visible: 是否可见, 可选参数: TRUE | FALSE | "legendonly" (之战时图例)

  • domain: 传入列表, 设置桑基图展示的区域

x: x轴展示的范围, 以整体的分数形式表示, 0~1的区间
y: y轴展示的范围, 以整体的分数形式表示, 0~1的区间
row: 如果存在网格,表示网格中的指定行
column: 如果存在网格,表示网格中的指定列

  • node: 传入列表, 指定节点信息

label: 设置每个节点的label, 用于展示文本信息, 用向量表示多个几点的label
groups: 节点的分组信息
x: 节点的标准化垂直位置
y: 节点的标准化水平位置
color: 节点的颜色, 用向量表示多个节点的颜色
pad: 设置节点之间的填充距离 (Default: 20)
thickness: 设置节点的宽度 (Default: 20)
line: 传入列表, 设置每个节点的边框信息

color: 边框的颜色
width: 边框的宽度

  • link: 传入列表, 设置连接的特征

label: 连接的标识, 展示文本信息, 使用向量表示多个连接的label
color: 连接的颜色
source: 连接的起始位置, 使用向量表示多个值
target: 连接的终止位置, 使用向量表示多个值
value: 表示流量的具体数值
line: 传入列表, 设置连接的边框信息

width: 边框的宽度
color: 边框的颜色

library(plotly)fig <- plot_ly(
  type = "sankey",
  orientation = "h",
  
  node = list(
    label = c("A1", "A2", "B1", "B2", "C1", "C2"),
    color = c("blue", "blue", "blue", "blue", "blue", "blue"),
    pad = 15,
    thickness = 20,
    line = list(
      color = "black",
      width = 0.5
    )
  ),
  
  link = list(
    source = c(0,1,0,2,3,3),  ## 每个值对应一个link的起始位置, 值代表node的index, 从0开始
    target = c(2,3,3,4,4,5),  ## 每个值对应一个link的终止位置, 值代表node的index, 从0开始
    value =  c(8,4,2,8,4,2)   ## 每个值对应一个link的流量
  ))fig <- fig %>% layout(
  title = "Basic Sankey Diagram",
  font = list(
    size = 10
  ))fig

Sankey_1

library(plotly)library(rjson)json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json"json_data <- fromJSON(paste(readLines(json_file), collapse=""))fig <- plot_ly(
    type = "sankey",
    domain = list(
      x =  c(0,1),
      y =  c(0,1)
    ),
    orientation = "h",
    valueformat = ".0f",
    valuesuffix = "TWh",

    node = list(
      label = json_data$data[[1]]$node$label,
      color = json_data$data[[1]]$node$color,
      pad = 15,
      thickness = 15,
      line = list(
        color = "black",
        width = 0.5
      )
    ),

    link = list(
      source = json_data$data[[1]]$link$source,
      target = json_data$data[[1]]$link$target,
      value =  json_data$data[[1]]$link$value,
      label =  json_data$data[[1]]$link$label
    )
  ) fig <- fig %>% layout(
    title = "Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a href='https://bost.ocks.org/mike/sankey/'>Mike Bostock</a>",
    font = list(
      size = 10
    ),
    xaxis = list(showgrid = F, zeroline = F),
    yaxis = list(showgrid = F, zeroline = F))fig

Sankey_2

误差线 (Error Bar)

  • 指定add_trace(..., error_y / error_x)绘制误差线

  • 注意需要先计算特征的方差/标准差合并到原数据中, 指定该变量绘制误差线

  • 误差线可以应用于barplot/Scatterplot /lineplot

  • 传入列表指定误差线特征

  • visable: 布尔值, 误差线是否可见

  • type: 确定用于生成误差线的规则, 可选参数有: "percent"(误差新的长度对应于基础数据的百分比) | "constant"(误差线长度为常量。在参数"value"中设置此常量) | "sqrt"误差线长度对应于数据的sqaure | "data"(误差线长度由参数"array"设置)

  • symmetric: 布尔值, 确定误差线在两个方向上的长度是否相同(垂直线的上/下,水平线的左/右)。

  • array: 设置与每个误差线长度相对应的数据, 值是相对于基础数据的。

  • value: 设置与误差线长度相对应的百分比(如果"type"设置为"percent")或常量(如果“type”设置为“constant”)(Default: 10)

  • color: 设置误差线的颜色

  • width: 设置误差线的宽度 (上下两条bar)

  • thickness: 设置误差线的厚度 (误差线整体的粗细) (Default: 2)

library(plotly)library(plyr)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)plot_ly() %>% 
  add_trace(data = data[which(data$supp == 'OJ'),], x = ~dose, y = ~length, type = 'bar', name = 'OJ',
            error_y = ~list(array = sd, color = '#000000')) %>% 
  add_trace(data = data[which(data$supp == 'VC'),], x = ~dose, y = ~length, type = "bar", name = 'VC',
            error_y = ~list(array = sd, color = '#000000'))

errorbar

图内文字和批注 (text and annotations)

  • add_text指定文字内容以及字体特征

  • 根据所绘制图形的不同文字的位置也有所不同

text

  • 简单的文字信息, 不包含箭头, 文本框

  • text: 指定文字的内容

  • textposition: 指定文字的位置, 可选参数: "top left" | "top center" | "top right" | "middle left" | "middle center" | "middle right" | "bottom left" | "bottom center" | "bottom right" | "outside" | "inside"

  • textfont: 传入列表参数, 指定文字的字体相关特征

family: 指定字体"Arial", "Balto", "Courier New"...
size: 指定字体大小
color: 指定字体颜色

library(plotly)

df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv", 
               stringsAsFactors = FALSE)
df <- df[which(df$year==2007 & df$continent=='Europe' & df$pop > 2.e6),]

fig <- plot_ly(df, type='bar', x = ~country, y = ~pop, text = ~lifeExp, name="",
               hovertemplate = paste('%{x}', '<br>lifeExp: %{text:.2s}<br>'),
               texttemplate = '%{y:.2s}', textposition = 'outside')

fig <- fig %>% layout(uniformtext=list(minsize=8, mode='hide'))
fig

text


annotations

  • 包含箭头, 文本框的批注信息

  • add_annotations指定批注信息

  • 也可以由layout(..., annotations)指定, 需要传入列表参数

  • visable: 布尔值, 批注是否可见

  • text: 设置与此批注关联的文本。Plotly使用HTML标记的子集来执行诸如换行符(
    )、粗体(<b></b>)、斜体(<i></i>)、超链接(<a href='…'></a>)

  • textangle: 设置字体的角度 (Default: 0)

  • font: 传入列表参数, 指定字体相关信息

family: 指定字体, 包括"Arial", "Balto", "Courier New", "Droid Sans"...
size: 字体大小
color: 字体颜色

  • width/height: 批注的宽高

  • opacity: 批注的透明度, 0 ~ 1的区间 (Default: 1)

  • align: 设置批注的水平对齐方式, 可选参数: "left" | "center" | "right" (Default: "center")

  • valign: 设置批注的数值对齐方式, 可选参数: "top" | "middle" | "bottom" (Default: "middle")

  • bgcolor: 设置批注的背景颜色 (Default: "rgba(0,0,0,0)")

  • bordercolor: 设置批注的边框颜色 (Default: "rgba(0,0,0,0)")

  • borderpad: 设置边框和文字内容之间的填充 (Default: 1)

  • borderwidth: 边框的宽度

  • showarrow: 布尔值, 是否显示箭头

  • arrowwidth: 箭头的宽度

  • arrowcolor: 箭头的颜色

  • arrowside: 指定箭头指向的方向, 可选参数: "end" | "start" | "end+start" | "none" (Default: "end")

  • arrowhead/startarrowhead: 指定结束/开始箭头的形状, 0 ~ 8的区间 (Default: 1)

  • arrowsize/startarrowsize: 指定结束/开始位置箭头的大小 (Default: 1)

  • standoff/startstandoff: 设置距离结束/开始位置的距离, 以像素为单位 (Default: 0)

  • ax/ay: 设置批注与图形的偏移量, 以像素为单位 (ax: 左右偏移; ay: 上下偏移)

  • xref/yref: 设置批注相对参考坐标轴, 可选参数 "x" | "x2"... | "y" | "y2"...

library(plotly)m <- mtcars[which.max(mtcars$mpg), ]a <- list(
  x = m$wt,
  y = m$mpg,           # 需要添加注释的位置
  text = rownames(m),  # 注释内容
  xref = "x",          # 参考坐标轴x
  yref = "y",          # 参考坐标轴y
  showarrow = TRUE,    # 展示箭头
  arrowhead = 7,       # 箭头类型 (7 -> 方块)
  ax = 20,             # x轴偏移量 (20px)
  ay = -40             # y轴偏移量 (40px))fig <- plot_ly(mtcars, x = ~wt, y = ~mpg)fig <- fig %>% add_markers()fig <- fig %>% layout(annotations = a)fig

Annotations

热图 (Heatmap)

  • add_trace(p, type="heatmap"[, ...])

  • visible: 是否显示trace, 可选参数: TRUE | FALSE | "legendonly" (Default: TRUE)

  • showlegend: 布尔值, 是否显示图例

  • legendgroup: 图例的分组, 在图例的分组绘制时使用

  • opacity: 透明度, 0 ~ 1的区间 (Default: 1)

  • x/y: 指定样本/特征

  • z: 指定绘制热图需要的值

  • colorscale: 设置绘制热图的色阶 (键值对形式), 指定0 (最小值) ~ 1 (最大值) 之间的颜色 (最小值和最大值必须指定), 例如: [[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]或者使用预设色阶字符串, 包括:
    (Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,Earth,Electric,Viridis,Cividis)

  • colors: 指定热图的颜色 (向量形式), 支持颜色插值函数, 如colorRamp(), 也支持预设颜色集, 包括: (Greys,YlGnBu,Greens,YlOrRd,RdBu,Blues等)

library(plotly)
## dim(volcano)
## [1] 87 61

fig <- plot_ly(z = volcano,    ## (data.frame/matrix/array)格式, 每一个值对应热图一个cell的颜色
               type = "heatmap")

fig

Heatmap1

m <- matrix(rnorm(9), nrow = 3, ncol = 3)
fig <- plot_ly(
    x = c("a", "b", "c"), y = c("d", "e", "f"),  ## 指定x/y
    z = m, type = "heatmap"
)

fig

Heatmap2

其他

  • 布局 (layout)

  • title: 传入列表, 标题的设置

  • text: 标题文本内容

  • font: 传入列表, 对标题的字体的设置

family: 对标题的字体设置
size: 标题的大小
color: 标题的颜色

  • xref: 横向偏移时参考的坐标轴 (Default: "container")

  • yref: 纵向偏移时参考的坐标轴 (Default: "container")

  • x: 在标准化坐标系中,相对于"xref"的x位置从"0" (左)到"1" (右) (Default: 0.5)

  • y: 在标准化坐标系中,相对于"yref"的y位置从“0”(左)到“1”(右) (Default: "auto")

  • xanchor: 设置标题相对于其x位置的水平对齐方式, 可选参数: "left" (左对齐) | "right" (右对齐) | "center" (居中) | "auto" (将"xref"除以3,并根据"x"的值自动计算"xanchor"值) (Default: "auto")

  • yanchor: 设置标题相对于其y位置的水平对齐方式, 可选参数: "left" (左对齐) | "right" (右对齐) | "center" (居中) | "auto" (将"yref"除以3,并根据"y"的值自动计算"yanchor"值) (Default: "auto")

  • pad: 设置标题的填充。每个填充值仅在相应设置了相应的"xanchor"/"yanchor"值时才适用

r: 右侧(right)的填充 (px) (Default: 0)
t: 顶部(top)的填充 (px) (Default: 0)
l: 左侧(left)的填充 (px) (Default: 0)
b: 底部(bottom)的填充 (px) (Default: 0)

  • showlegend: 布尔值, 是否显示图例

  • legend: 传入列表, 设置图例的特征

  • bgcolor: 图例的背景颜色

  • bordercolor: 边框颜色

  • borderwidth: 边框的宽度 (Default: 0)

  • font: 传入列表, 设置图例的字体特征

family: 设置图例文字的字体
color: 设置图例文字的颜色
size: 设置图例文字的大小 (大于1)

  • orientation: 设置图例的方向, 可选参数: "v" (竖直) | "h" (水平)

  • traceorder: 确定图例项的显示顺序, 可选参数: "reversed" (与normal相反) | "grouped" (则项目将分组显示(当提供跟踪"legendgroup"时) | "reversed+grouped" (与"grouped"按相反的顺序显示) | "normal" (与输入数据相同的顺序从上到下显示)

  • tracegroupgap: 设置图例组之间的垂直间距 (以px为单位) (Default: 10)

  • itemsizing: 确定图例项符号是否具有相应的trace进行缩放, 可选参数: "trace" | "constant"

  • x/y: 图例的坐标 (-2 ~ 3之间)

  • xanchor: 图例的水平定位, 可选参数: "auto" | "left" | "center" | "right"

  • yanchor: 图例的竖直定位, 可选参数: "auto" | "top" | "middle" | "bottom"

  • title: 传入列表, 设置图例标题的特征

text: 设置图例标题的文字内容
side: 图例标题相对于图例的位置, 可选参数:"top" | "left" | "top left"
font: 传入列表, 设置图例标题的字体相关特征

family: 设置字体
color: 设置文字颜色
size: 设置文字大小

  • margin: 设置图形的外边距

l/r/t/b: 分别设置左(left), 右(right), 上(top, Default: 100), 下(bottom) (Default: 80)
pad: 外边距的填充量(px) (Default: 0)
autoexpand: 自动扩展, 根据图例, 标题等因素对图形进行动态扩展 (Default: TRUE)

  • width: 设置图形整体的宽度 (Default: 700)

  • height: 设置图形整体的高度 (Default: 450)

  • font: 设置图形中文字的特征

family: 字体 (Default: ""Open Sans", verdana, arial, sans-serif")
color: 颜色 (Default: 12)
size: 大小 (Default: "#444")

  • uniformtext: 统一文本

mode: 确定如何在每个跟踪类型之间统一不同文本元素的字体大小, 如果计算的文本大小小于由minsize使用"hide"选项隐藏文本; 使用"show"选项显示文本, 而不需要进一步缩小缩放
minsize: 设置相同类型trace之间的最小文本大小 (Default: 0)

  • paper_bgcolor: 设置图纸的背景颜色

  • plot_bgcolor: 设置图形的背景颜色

  • 坐标轴 (Axes)

  • visible: 布尔值, 坐标轴是否可见

  • color: 坐标轴的颜色 (Default: "#444")

  • title: 坐标轴的标题

text: 标题的内容
standoff: 设置轴标签和标题文本之间的间距
font: 标题的字体

family: 字体
size: 大小
color: 颜色

  • type: 设置坐标轴的类型, 可选参数: "-" | "linear" | "log" | "date" | "category" | "multicategory" (Default: "-")

  • autorange: 布尔值, 是否根据输入数据自动计算坐标轴的范围 (Default: TRUE)

  • rangemode: 适用于线性轴, 则根据输入数据的极值计算范围, 可选参数: "normal" | "tozero" (坐标轴扩展到0) | "nonnegative" (坐标轴始终非负)

  • range: 手动设置坐标轴的范围

  • fixedrange: 布尔值, 确定此轴是否可缩放, 如果为TRUE, 则禁用缩放

  • tickmode: 设定轴的刻度模式, 可选参数: "auto" (通过"nticks"设置刻度数) | "linear" (刻度的位置由起始位置"tick0"和刻度步长"dtick"决定) | "array" (通过"tickvals"设置ticks的位置,tick文本为"ticktext")

  • nticks: 指定特定轴的最大刻度数

  • tick0: 设置坐标轴上第一个刻度的位置

  • dtick: 设置刻度步长

  • tickvals: 传入数组, 设置该坐标轴上的刻度出现的值

  • ticktext: 每一个tickvals出现的刻度上的显示的文本

  • ticks: 是否绘制刻度, 可选参数: "outside" | "inside" | ""

  • mirror: 确定坐标轴/刻度是否镜像到另一侧, 可选参数: TRUE | "ticks" | FALSE | "all" | "allticks"

  • ticklen: 设置刻度长度 (px) (Default: 5)

  • tickwidth: 设置刻度宽度 (px) (Default: 1)

  • tickcolor: 设置刻度的颜色 (Default: "#444")

  • showticklabels: 布尔值, 是否绘制刻度标签

  • automargin: 确定长刻度标签是否自动扩展外边距

  • tickfont: 刻度的字体特征

family: 字体
color: 颜色
size: 大小

  • tickangle: 刻度的角度

  • tickprefix: 刻度的前缀 (Default: "")

  • showtickprefix: 指定哪些刻度会展示签证, 可选参数: "all" | "first" | "last" | "none" (Default: "all")

  • ticksuffix: 刻度的后缀 (Default: "")

  • showticksuffix: 指定哪些刻度会展示签证, 可选参数: "all" | "first" | "last" | "none" (Default: "all")

  • showline: 布尔值, 是否绘制此坐标轴的边界线

  • linecolor: 坐标轴的颜色 (Default: "#444")

  • linewidth: 设置坐标轴的宽度 (Default: 1)

  • showgrid: 确定是否绘制网格线。如果为"TRUE", 则在每个刻度线处绘制网格线

  • gridcolor: 设置网格线的颜色 (Default: "#eee")

  • gridwidth: 设置网格线的宽度 (Default: 1)

  • zeroline: 布尔值, 确定是否沿该轴的0值绘制直线

  • zerolinecolor: 设置0线的颜色 (Default: "#444")

  • zerolinewidth: 设置0线的宽度 (Default: 1)

  • side: 确定坐标轴绘制的位置, 可选参数: "top" | "bottom" | "left" | "right"

  • domain: 设置此轴的域 (Default: [0, 1])

  • anchor: 如果设置为相反的字母轴id (例如"x2", "y"), 则此轴将绑定到相应的相反字母轴。如果设置为free,则该轴的位置由position决定。

  • position: 设置坐标轴在图形中的位置 (在标准化坐标中), 只有当anchor设置为free时才有效果

  • ggplot2图形转换plotly: ggplotly(p)

  • 导出静态图片

  1. 首先需要下载orca(https://github.com/plotly/orca/releases), 选择对应系统的版本

  2. 安装orca并添加到环境变量

  3. 安装额外依赖: install.packages("processx")

  • p: 需要导出的plotly对象

  • file: 导出的文件名

  • width: 生成文件后图片的宽度, 默认使用layout.width生成图片的宽度

  • height: 生成文件后图片的高度, 默认使用layout.height生成图片的高度

  • scale: 图片的缩放比例

  • verbose: 是否在控制台打印日志信息

library(plotly)if (!require("processx")) install.packages("processx")fig <- plot_ly(z = ~volcano) %>% add_surface()orca(fig, "surface-plot.png", scale = 0.5, verbose = T)## exported surface-plot, in 1822.699999 ms## \## done with code 0 in 1.82 sec - all task(s) completed

orca_static_plot



作者:nnlrl
链接:https://www.jianshu.com/p/56f70f667570


文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐