plot_ly function
The plotly package allows creating interactive charts in R based on the plotly.js JavaScript library. The charts allow zooming, panning, hovering over the elements to see their values and hiding groups clicking on the legend, and they can be embedded in HTML documents, R Markdown, Quarto or Shiny apps.
After installing the package, use the plot_ly function to create a chart. Pass your data to data and the variables to x and y with a tilde (~) before their names. The type of chart is set with type and, for scatter traces, mode sets whether to draw markers, lines or both.
# install.packages("plotly")
library(plotly)
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length,
type = "scatter", mode = "markers")
Instead of setting the type you can add layers to the chart with the add_* functions, such as add_markers, add_lines, add_bars, add_boxplot, add_histogram or add_surface. Note that you can chain them with the pipe operator. In the following example we are creating a grouped bar chart with add_bars, mapping the groups to color and setting barmode = "group" inside layout.
df <- data.frame(x = rep(c("Q1", "Q2", "Q3", "Q4"), 3),
group = rep(c("A", "B", "C"), each = 4),
y = c(12, 18, 15, 22, 9, 14, 20, 17, 6, 11, 13, 19))
plot_ly(df, x = ~x, y = ~y, color = ~group,
colors = c("#5E60CE", "#48BFE3", "#72EFDD")) |>
add_bars() |>
layout(barmode = "group")
Map a variable to color to color the elements by group. The palette is set with the colors argument, which accepts a vector of colors or the name of a palette, such as "Set2" or "viridis". A legend will be added automatically.
plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
color = ~Species,
colors = c("#264653", "#E9C46A", "#E76F51"),
type = "scatter", mode = "markers")
Continuous color scale
If the variable is numeric a continuous color scale (colorscale) will be used instead. In this case you can pass a palette name or a vector with the colors of the gradient to colors.
plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
color = ~Petal.Width, colors = "viridis",
type = "scatter", mode = "markers")
The information displayed when hovering over the elements can be customized with hovertemplate. Use %{x} and %{y} to display the values of the axes and text to pass additional information, which can be displayed with %{text}. Add <extra></extra> to remove the name of the trace from the box.
plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
type = "scatter", mode = "markers",
text = ~Species,
hovertemplate = paste("Species: %{text}<br>",
"Sepal length: %{x}<br>",
"Petal length: %{y}<extra></extra>"))
The title and the axes are customized with the layout function. The axes are set with lists passed to xaxis and yaxis, which allow changing the title, the range or the grid, among others. Note that to remove the title of an axis you can set it to an empty string.
plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
type = "scatter", mode = "markers") |>
layout(title = "Iris data set",
xaxis = list(title = "Sepal length", range = c(4, 8.5)),
yaxis = list(title = "", showgrid = FALSE))
The legend can also be customized inside layout. Pass a list to legend to set its title with title, display it horizontally with orientation = "h" and change its position with x and y. If you want to remove it set showlegend = FALSE.
plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
color = ~Species,
type = "scatter", mode = "markers") |>
layout(legend = list(title = list(text = "Species"),
orientation = "h",
x = 0, y = -0.2))
subplot
The subplot function allows combining several plotly charts in the same figure. Use nrows to set the number of rows, heights or widths for the relative size of each plot and shareX or shareY to share the axes, so zooming on one plot will also zoom the other.
p1 <- plot_ly(iris, x = ~Sepal.Length, type = "histogram", name = "Histogram",
color = I("#5E60CE"))
p2 <- plot_ly(iris, x = ~Sepal.Length, type = "box", name = "Box plot",
color = I("#48BFE3"))
subplot(p1, p2, nrows = 2, shareX = TRUE, heights = c(0.7, 0.3))
The toolbar (modebar) displayed on the top right corner of the charts can be customized with the config function. You can remove it with displayModeBar = FALSE, remove the plotly logo with displaylogo = FALSE or remove some buttons with modeBarButtonsToRemove.
plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
type = "scatter", mode = "markers") |>
config(displaylogo = FALSE,
modeBarButtonsToRemove = c("lasso2d", "select2d"))
The charts can be saved as HTML files with the saveWidget function of the htmlwidgets package, which keeps the interactivity. If you need a static image you can use the camera icon of the toolbar to download a PNG or the save_image function, which requires the kaleido Python library.
p <- plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length,
type = "scatter", mode = "markers")
# HTML file
htmlwidgets::saveWidget(p, "plot.html", selfcontained = TRUE)
# Static image
save_image(p, "plot.png")
If you prefer to create your charts with ggplot2 you can convert them into interactive charts with the ggplotly function. For interactive maps you can also use the leaflet package.
Learn statistics from the basics to advanced techniques, clearly explained
Go to site
See also