-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotly.qmd
More file actions
executable file
·405 lines (298 loc) · 18.3 KB
/
plotly.qmd
File metadata and controls
executable file
·405 lines (298 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
---
title: "Plotting Details"
format:
html:
css: Extras/custom.scss
include-in-header: Extras/copy-all-code.html
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
echo = TRUE,
eval = TRUE
)
```
```{r}
#| echo: false
#| label: setup
#| eval: true
#| message: false
library(Pmetrics)
library(magrittr)
library(dplyr)
library(plotly)
r_help <- function(pkg, name) {
glue::glue("[`{name}`](https://rdrr.io/pkg/{pkg}/man/{name}.html)")
}
gh_help <- function(name) {
glue::glue("[`{name}`](https://lapkb.github.io/Pmetrics/reference/{name}.html)")
}
pmetrics <- function(){
knitr::asis_output("[Pmetrics]{style=\"color: #841010; font-family: 'Arial', Arial, sans-serif; font-weight: 900;\"}")
}
library(gt)
custom_table <- function(tab){
read.csv(file.path("Data",tab), na.strings = ".") %>% gt() %>%
tab_style(
style = list(
cell_fill(color = "black"),
cell_text(color = "white", weight = "bold")
),
locations = cells_column_labels(everything())
)
}
```
## Overview
As of version 2, *Pmetrics* uses the *plotly* package for most plots. Plots
made with plotly are interactive, so that moving your cursor over them
results in pop up information being displayed. A nice feature of plotly is the `ggplotly` command which takes any *ggplot* plot object and turns it into a plotly plot. This route doesn't provide complete control of plotly objects, so Pmetrics uses plotly from the ground up.
However, the documentation for plotly is a bit complex and often lacking in
sufficient examples. This vignette attempts to orient you to the specific
aspects of plotly most relevant to Pmetrics.
## General
Plotly is based on a foundation of lists. Most plot elements are lists whose
arguments control characteristics of the elements. Pmetrics chiefly uses only
a handful of the elements.
Full descriptions of plotly elements and options to control them can be accessed
by typing `plotly::schema()` into the R console. If you have already loaded
plotly you can just type `schema()`. You will see something like the menu below
in the Viewer tab in Rstudio.

In plotly, the [traces](#traces) items control appearance of the data. The [layout](#layout) items control everything to do with the appearance of the
axes and the legend.
## Traces
Pmetrics almost exclusively uses scatter traces, and those elements can be
referenced by expanding traces `r knitr::asis_output("\U25B6")` scatter
`r knitr::asis_output("\U25B6")` attributes.
There are many such attributes, but the most commonly used and accessible to the user are line and marker.
### Line attributes
All plotly plots in Pmetrics have a `line` argument which maps to the *line* attribute
of a plotly scatter trace.
When Pmetrics detects a boolean argument, e.g. `TRUE` or `FALSE` it either plots
the default line or suppresses the line altogether. A good example of this is the
`line` argument to `plot.PM_op` to generate an observed vs. predicted plot. In this
function, `line` is a list of named lines that can be plotted. If *NPex* is a
*PM_result* object loaded with `PM_load()` then the default is
`NPex$plot$op(line = list(lm = F, loess = T, ref = T))`.This means that a
linear model (regression) will not be plotted, a loess regression will be plotted,
and a reference line with slope = 1 and intercept = 0 will also be plotted. If we
are happy with all the defaults, we simply need to call the plot method for the
*PM_op* object field in NPex.
```{r}
#| label: "op1"
NPex$op$plot()
```
Below is a simple example of how to change the default lines plotted, but retain
the default formatting. Now a linear regression (using the R `lm` function) is plotted with a reference line, but not a loess regression.
```{r}
#| label: "op2"
NPex$op$plot(line = list(lm = T, loess = F, ref = T))
```
The default formats for lines may differ from function to function and are indicated
in the help files. However all lines may be formatted using three arguments as a **list**.
* `color` Specify the color of the line as a character with either the
- name: a good reference in R is to use the `colors()` function, e.g. "dodgerblue"
- hexadecimal code: this can be searched on the web, and is specified as a character
with leading "#" followed by 6 hexidecimal digits, two each for Red, Green, Blue, e.g. "#C0C0C0".
Adding an extra two digits specifies transparency, with 00 fully transparent and FF fully opaque,
e.g. #C0C0C066".
- a plotly function `toRGB` which takes a color name and alpha (transparency) value on a scale of 0 - 1,
e.g., `toRGB("red", 0.5)`.
* `width` Units are pixels.
* `dash` Sets the dash style of lines. Set to a dash type string (*solid*,*dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)
```{r}
#| label: "op3"
NPex$op$plot(line = list(loess = list(color = "orange", dash = "dashdot", width = 2)))
```
Note the default is `lm = F` and `ref = T`, so we don't need to specify them if that's what we want.
### Marker attributes
All plotly plots in Pmetrics have a `marker` argument which maps to the *marker* attribute
of a plotly scatter trace.
When Pmetrics detects a boolean argument, e.g. `TRUE` or `FALSE` it either plots
the default marker or suppresses the marker altogether. A good example of this is also the
`marker` argument to `plot.PM_op` to generate an observed vs. predicted plot. In this
function, `marker` controls the plotting symbol. If *NPex* is a
*PM_result* object loaded with `PM_load()` then the default is
`NPex$plot$op(marker = T)`.This means that the symbols will be plotted with default
formatting. If we are happy with all the defaults, we simply need to call the plot method for the
*PM_op* object field in NPex.
```{r}
#| label: "op4"
NPex$op$plot()
```
The default formats for markers may differ from function to function and are indicated
in the help files. However all markers may be formatted using most commonly four arguments as a **list**.
* `color` Specify the color of the marker fill as a character with either the
- name: a good reference in R is to use the `colors()` function, e.g. "dodgerblue"
- hexadecimal code: this can be searched on the web, and is specified as a character
with leading "#" followed by 6 hexidecimal digits, two each for Red, Green, Blue, e.g. "#C0C0C0".
Adding an extra two digits specifies transparency, with 00 fully transparent and FF fully opaque,
e.g. #C0C0C066".
- a plotly function `toRGB` which takes a color name and alpha (transparency) value on a scale of 0 - 1,
e.g., `toRGB("red", 0.5)`.
* `size` Units are points.
* `symbol` Either a character name or the numeric value associated with the character.
See `schema()` traces `r knitr::asis_output("\U25B6")` scatter
`r knitr::asis_output("\U25B6")` attributes `r knitr::asis_output("\U25B6")`
marker `r knitr::asis_output("\U25B6")` symbol `r knitr::asis_output("\U25B6")`
values for all the possibilities, e.g. "circle-open" is equivalent to 100, "square"
is equivalent to 1, and "diamond-open-dot" is equivalent to 302.
* `opacity` On a scale of 0 (transparent) to 1 (opaque).
Any other marker attribute is possible, including `line`, which itself is a list
to specify attributes of the outline for a marker.
```{r}
#| label: "op5"
NPex$op$plot(marker = list(
color = "slategray", size = 12,
opacity = 0.5, line = list(color = "navy")
))
```
## Layout
Layout layout `r knitr::asis_output("\U25B6")` layoutAttributes
`r knitr::asis_output("\U25B6")` displays all the options for the layout. Pmetrics plot functions currently only provide access to the following layout options:
* `legend`
* `xaxis`
* `yaxis`
* `title`
Details of how each is accessed are below.
### Legend
In all relevant Pmetrics plotly plots, the argument for legend can take one of three forms:
`TRUE`, `FALSE`, or a list. The first and second options choose to include the default legend or to suppress the legend, respectively.
Specifying `legend` as a list allows for detailed formatting of the legend using
any of the attributes documented by typing `schema()` into the R console, and expanding layout `r knitr::asis_output("\U25B6")` layoutAttributes
`r knitr::asis_output("\U25B6")` legend. These can be included as elements in the legend list.
Here's a basic legend.
```{r}
#| label: "data1"
NPex$data$plot(legend = T)
```
...and a more complex one.
```{r}
#| label: "data2"
NPex$data$plot(
marker = list(color = "navy"),
line = list(
join = FALSE,
pred = list("post")
),
legend = list(
x = 0.75,
y = 0.85,
borderwidth = 1,
bgcolor = "antiquewhite"
),
xlim = c(119, 146)
)
```
### X axis and Y axis
Several arguments in most Pmetrics plots map to plotly list elements that control the formatting of the x- and y-axes. A full list of these elements can be viewed by typing `schema()` into the R console and expanding layout `r knitr::asis_output("\U25B6")` layoutAttributes
`r knitr::asis_output("\U25B6")` xaxis / yaxis.
* `log` When `TRUE`, maps to `yaxis = list(type = "log")` and sets the y axis to
log scale.
* `xlim` and `ylim` If specified as vectors of length two, e.g. `xlim = c(0, 100)`,
map to `xaxis = list(range = xlim)` and the same for the y axis.
* `xlab` and `ylab` If specified as character vectors of length 1, e.g. `xlab = "Time"`,
map to `xaxis = list(title = list(text = xlab))` and the same for the y axis. However, unlike the simpler `log`, `xlim`, and `ylim` arguments, `xlab` and `ylab` can also be specified as lists to control the formatting of the axes labels. The lists follow the plotly conventions:
- `text` The name of the axis
- `font` The formatting of the label, itself a list:
- `color` Color of the text
- `family` The HTML font family, e.g. "Arial" or "Times New Roman"
- `size` Size in points
If you only specify a list for `xlab` it will be applied to `ylab`. To format them independently, specify a list for both.
``` {r}
#| label: "data3"
NPex$data$plot(xlab = "Time (h)", ylab = "Rifapentine (mg/L)")
```
``` {r}
#| label: "data4"
NPex$data$plot(xlab = list(text = "Time (h)", font = list(color = "slategrey", family = "Times New Roman", size = 18)))
# notice that ylab is also formatted in the same way
```
For greater control over the axes, e.g. tick placement, coloring, etc., the "..." argument in plots is coded to pass arguments to the xaxis and yaxis lists. This allows access to any attribute. If axis attributes are passed through ... in a named list, e.g. `xaxis = list(linecolor = "red")`, then they will be specific to that axis. However, if the attributes are passed through ... directly, without inclusion in an `xaxis` or `yaxis` list, they will apply to both the axes, e.g. `$plot(...,`linecolor = "red")` will color the xaxis and yaxis lines red.
``` {r}
#| label: "data5"
NPex$data$plot(xaxis = list(linecolor = "firebrick", ticks = "inside"))
# only affects x axis since formatting within xaxis list
```
``` {r}
#| label: "data6"
NPex$data$plot(linecolor = "dodgerblue", ticks = "outside")
# formatting affects both axes since arguments are outside xaxis or yaxis lists
```
### Title
All Pmetrics plotly plots have a `title` argument which maps to the attributes controlling the text and formatting of the plot title. A full list of these elements can be viewed by typing `schema()` into the R console and expanding layout `r knitr::asis_output("\U25B6")` layoutAttributes
`r knitr::asis_output("\U25B6")` title. These are the same as for the axes titles, i.e. `text` and `font`, plus additional attributes to control the positioning of the title. The most common will be `x` to control the horizontal placement from 0 (left) to 1 (right) of the plot, and `y` to control the vertical placement from 0 (bottom) to 1 (top). The default for `x` is 0.5 (middle) and for `y` it is "auto", which puts the bottom of the title text onto the vertical center of the top margin.
By default the title text is oriented around the `x` value automatically ("auto") via the `xanchor` attribute, but this could also be "left", "right", or "center" to make the text begin at, end at, or span the `x` value, respectively. Analogous behavior can be controlled by the `yanchor` attribute for which part of the text lines up with the `y` value: "top", "middle", or "bottom". The default is "auto".
```{r}
#| label: "data7"
NPex$data$plot(title = list(text = "Rifapentine", yanchor = "top"), ylab = "Concentration (mg/L)", xlab = "Time (h)")
```
## Shapes
Shapes in plotly are part of the layout and detailed by typing `schema()` into the R console and expanding layout `r knitr::asis_output("\U25B6")` layoutAttributes
`r knitr::asis_output("\U25B6")` shapes `r knitr::asis_output("\U25B6")` shape. Oddly, there is no native ability in R plotly to add shapes to an existing plot,
so Pmetrics has a custom function `add_shapes` which does the job.
The workflow is to first create a plot. All Pmetrics functions return the plot object so you can either assign the plot call to a variable, e.g. `p <- plot(...)` or use the current plot via plotly's `last_plot` function, which is the default value for `add_shapes`.
Since reference lines are by far the most common shape to add, Pmetrics has a helper function called `ab_line`, which is very similar to the workflow in base R that uses the `abline` function to add a line to the current plot.
```{r echo = T, eval = T, label = "shapes1"}
NPex$data$plot() %>%
add_shapes(ab_line(h = 5, line = list(color = "green", width = 3)))
```
Note the use of the pipe operator `%>%` to pipe the plot directly into the `add_shapes` function. This is not mandatory, since `add_shapes` by default takes the current plot as its target. If you have a previously saved plot in a variable, you can add a shape any time by supplying that variable to `add_shapes`, for example `add_shapes(p, ab_line(h = 5))`.
It is possible to add other shapes, but it will require more manual effort as there are no Pmetrics helper functions to add circles, rectangles, or paths. Here's an example of adding a circle.
```{r echo = T, eval = T, label = "shapes2"}
NPex$data$plot() %>%
add_shapes(shape = list(
type = "circle", x0 = 122, x1 = 132,
y0 = 15, y1 = 22
))
```
The values for x0 and x1 determine the left and right extent, and for y0 and y1 the bottom and top of the circle. Coordinates are absolute, unless you include `xref = "paper"` and/or `yref = "paper"` An additional line list can control formatting.
## Annotations
Here plotly does provide two functions to add annotations to plots as labels or as floating text.
`plotly::add_annotations()` will add labels to data, allowing for connection between the data point and the label by an arrow. The options are detailed by typing `?add_annotations` into the R console. However, rather than following the hyperlink there to get additional information on options, you can get more help by typing `schema()` into the R console and expanding layout `r knitr::asis_output("\U25B6")` layoutAttributes
`r knitr::asis_output("\U25B6")` annotations `r knitr::asis_output("\U25B6")` items `r knitr::asis_output("\U25B6")`annotation.
Similarly, `plotly::add_text()` adds labels/text to a plot, but without the connecting line. The options are detailed by typing `?add_text` into the R console. You can get more options by typing `schema()` into the R console and expanding traces `r knitr::asis_output("\U25B6")` scatter
`r knitr::asis_output("\U25B6")` attributes `r knitr::asis_output("\U25B6")` text, textfont, and textposition. The others (textpositionsrc, textsrc, texttemplate, textemplatesrc) are more obscure and not needed.
Annotations with connecting arrows...
```{r echo = T, eval = T, label = "annot1"}
NPex$data$plot() %>%
add_annotations(text = ~id, x = ~time, y = ~out, data = NPex$data$data %>% filter(out>0)) # use the raw data to obtain the id labels and positions
```
Text without arrows...
```{r echo = T, eval = T, label = "annot2"}
NPex$data$plot() %>%
add_text(
text = ~id, x = ~time, y = ~out, textposition = "top right",
textfont = list(color = "navy", size = 12),
data = NPex$data$data %>% filter(out>0)
)
```
A single text item...
```{r echo = T, eval = T, label = "annot3"}
NPex$data$plot() %>%
add_text(x = 125, y = 2, text = "<b>Limit of quantification</b>", textfont = list(size = 12)) %>%
add_shapes(shape = ab_line(h = 1.8))
```
Notice how the tidyverse pipe `%>%` lets you string together commands. [Tidyverse](https://www.tidyverse.org) is a powerful set of libraries for R that permit methodical, advanced data manipulation. You can load it with `library(tidyverse)`. In the plot below, we return to `add_annotations` to demonstrate that it gives you more control over the formatting. Generally, this function is likely the more useful to add text pop ups or to label data. Notice the use of the html tags <b></b> to surround the text and make it bold. You can also use `<i></i>` for italics, but plotly does not support `<u></u>` for underline.
```{r echo = T, eval = T, label = "annot4"}
NPex$data$plot() %>%
add_annotations(x = 125, y = 2, text = "<i>Limit of quantification</i>", font = list(size = 10, color = "white"), showarrow = F, bgcolor = "navy", bordercolor = "black") %>%
add_shapes(
shape = ab_line(h = 1.8, line = list(color = "navy", dash = "dashdot"))
)
```
## Exporting
### Images
Although the plotly team is working on methods to export plots to images via scripting, they require installation of additional components =. So Pmetrics includes a wrapper function `export_plotly()` which you can use to install the necessary components and export images.
Exporting a plotly plot to a static image can be accomplished in two additional ways.
The first is to select the Export button from the Viewer window in Rstudio when the desired plot is displayed. This gives the option to save the plot as a .png, .jpeg, or .tiff. You cannot save as a .pdf with this method.

The second option is to click the camera icon that appears in the top right of a plotly plot when you mouse over the plot.

This gives you the option to download and save the file as a .png.
### PDFs
To export to a .pdf, you can also use `export_plotly()` in Pmetrics. You can also
open the plot in a browser.

From there you should be able to export the image as .pdf file.