第 13 章 交互图形
plotly 是一个功能非常强大的绘制交互式图形的 R 包。它支持下载图片、添加水印、自定义背景图片、工具栏和注释39 等一系列细节的自定义控制。下面结合 JavaScript 库 plotly.js 一起介绍,帮助文档 ?config 没有太详细地介绍,所以我们看看 config() 函数中参数 ... 和 JavaScript 库 plot_config.js 中的功能函数是怎么对应的。图13.1 中图片下载按钮对应 toImageButtonOptions 参数, 看 toImageButtonOptions 源代码,可知,它接受任意数据类型,对应到 R 里面就是列表。 watermark 和 displaylogo 都是传递布尔值(TRUE/FALSE),具体根据 JavaScript 代码中的 valType (参数值类型)决定,其它参数类似。另一个函数 layout 和函数 config() 是类似的,怎么传递参数值是根据 JavaScript 代码来的。
toImageButtonOptions: {
valType: 'any',
dflt: {},
description: [
'Statically override options for toImage modebar button',
'allowed keys are format, filename, width, height, scale',
'see ../components/modebar/buttons.js'
].join(' ')
},
displaylogo: {
valType: 'boolean',
dflt: true,
description: [
'Determines whether or not the plotly logo is displayed',
'on the end of the mode bar.'
].join(' ')
},
watermark: {
valType: 'boolean',
dflt: false,
description: 'watermark the images with the company\'s logo'
},library(plotly, warn.conflicts = FALSE)
plot_ly(diamonds,
x = ~clarity, y = ~price,
color = ~clarity, colors = "Set1", type = "box"
) %>%
config(
toImageButtonOptions = list(
format = "svg", width = 450, height = 300,
filename = paste("plot", Sys.Date(), sep = "_")
),
modeBarButtons = list(list("toImage")),
watermark = FALSE,
displaylogo = FALSE,
locale = "zh-CN",
staticPlot = TRUE,
showLink = FALSE,
modeBarButtonsToRemove = c(
"hoverClosestCartesian", "hoverCompareCartesian",
"zoom2d", "zoomIn2d", "zoomOut2d",
"autoScale2d", "resetScale2d", "pan2d",
"toggleSpikelines"
)
) %>%
layout(
template = "plotly_dark",
images = list(
source = "https://images.plot.ly/language-icons/api-home/r-logo.png",
xref = "paper",
yref = "paper",
x = 1.00,
y = 0.25,
sizex = 0.2,
sizey = 0.2,
opacity = 0.5
),
annotations = list(
text = "DRAFT", # 水印文本
textangle = -30, # 逆时针旋转 30 度
font = list(
size = 40, # 字号
color = "gray", # 颜色
family = "Times New Roman" # 字族
),
opacity = 0.2, # 透明度
xref = "paper",
yref = "paper",
x = 0.5,
y = 0.5,
showarrow = FALSE # 去掉箭头指示
)
)图 13.1: 自定义细节
| 参数 | 作用 |
|---|---|
| displayModeBar | 是否显示交互图形上的工具条,默认显示 TRUE40。 |
| modeBarButtons | 工具条上保留的工具,如下载 "toImage",缩放 "zoom2d"41。 |
| modeBarButtonsToRemove | 工具条上要移除的工具,如下载和缩放图片 c("toImage", "zoom2d")。 |
| toImageButtonOptions | 工具条上下载图片的选项设置,包括名称、类型、尺寸等。42 |
| displaylogo | 是否交显示互图形上 Plotly 的图标,默认显示 TRUE43。 |
| staticPlot | 是否将交互图形转为静态图形,默认 FALSE。 |
| locale | 本土化语言设置,比如 "zh-CN" 表示中文。 |
https://plotly.com/r/reference/#layout-scene-annotations-items-annotation-font↩︎
完整的列表见 https://github.com/plotly/plotly.js/blob/master/src/components/modebar/buttons.js。↩︎
设置下载图片的尺寸,还可设置为 PNG 格式,SVG 格式图片,可借助 rsvg 的
rsvg_pdf()函数转化为 PDF 格式 https://github.com/ropensci/plotly/issues/1556#issuecomment-505833092。↩︎