Skip to content

Commit 09ba7b9

Browse files
committed
Add ggplotly example
1 parent 6d99f9d commit 09ba7b9

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

DESCRIPTION

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,6 @@ Suggests:
3030
purrr,
3131
gapminder,
3232
stringr,
33-
testthat (>= 2.1.0)
33+
testthat (>= 2.1.0),
34+
plotly
3435
VignetteBuilder: knitr

vignettes/cookbook/_chart-types.Rmd

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,41 @@ bar_data |>
284284
caption = "Source: Gapminder"
285285
)
286286
```
287+
288+
289+
## Interactive charts
290+
291+
To make a `ggplot2` chart interactive, use `ggplotly()` from the `plotly` package. Note however that `ggplotly()` has a number of 'quirks', including the following:
292+
293+
* sgplot uses the 'sans' font family, however `plotly` does not recognise this font. To work around this you should add a further call to `theme` to set the font family for text to `""`.
294+
295+
* Subtitles and captions are not supported in `ggplotly()`. As stated elsewhere in this guidance, titles and subtitles should ideally be included in the body of text surrounding a chart rather than embedded in the chart itself, and so this is hopefully not a big issue. This example therefore has no title, subtitle or caption.
296+
297+
```{r interactive-charts}
298+
#| fig.alt = "An interactive bar chart using sgplot theme and dark blue colour. A tooltip appears when hovering over each bar."
299+
300+
p <-
301+
bar_data |>
302+
# Format text for tooltips
303+
mutate(tooltip = paste0(
304+
"Country: ", country, "\n",
305+
"Life Expectancy: ", round(lifeExp, 1)
306+
)) |>
307+
ggplot(aes(x = reorder(country, -lifeExp), y = lifeExp, text = tooltip)) +
308+
geom_col(fill = sg_colour_values["dark-blue"]) +
309+
theme_sg(ticks = "x") +
310+
theme(text = element_text(family = "")) +
311+
scale_y_continuous(expand = c(0, 0)) +
312+
labs(
313+
x = NULL,
314+
y = NULL
315+
)
316+
317+
plotly::ggplotly(p, tooltip = "text") |>
318+
plotly::config(
319+
modeBarButtons = list(list("resetViews")),
320+
displaylogo = FALSE
321+
)
322+
```
323+
324+
sgplot currently only works with `ggplot2` charts, however there are plans to [develop the package further to support interactive Highcharts](https://github.com/DataScienceScotland/sgplot/issues/5) produced using the [`highcharter`](https://jkunst.com/highcharter) package.

0 commit comments

Comments
 (0)