Open In App

How to Remove Option Bar from ggplotly Using R

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In interactive visualizations created with the plotly package in R, a toolbar appears by default when the plot is rendered. This toolbar allows users to zoom, pan, save images, and reset the view. However, in certain cases, you may want to remove this toolbar (also known as the options bar) to provide a cleaner visualization, particularly for embedding in web applications or reports where minimal interface elements are desired.

The Toolbar (Option Bar)

The option bar in a plotly plot provides several interactive tools:

  • Zoom in/out
  • Pan
  • Box select
  • Reset view
  • Save as PNG

This toolbar may be useful for user interactivity but might not always fit into the design requirements of a static report or custom application. let's discuss step by step How to Remove the Options Bar from ggplotly Using R Programming Language.

Step 1: Install and Load Necessary Libraries

Ensure you have the ggplot2 and plotly libraries installed. Load them using the following commands:

R
install.packages("ggplot2")
install.packages("plotly")
library(ggplot2)
library(plotly)

Step 2: Create a ggplot Plot

First, create a simple plot using ggplot2. For this example, let’s use the classic mtcars dataset to create a scatter plot of mpg vs wt:

R
# Create a ggplot object
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
    geom_point(color = "blue") +
    labs(title = "Scatter plot of MPG vs Weight",
         x = "Weight (1000 lbs)",
         y = "Miles per Gallon (MPG)")

p

Output:

gh
Create a ggplot Plot

Step 3: Convert to Plotly Using ggplotly()

Convert the ggplot2 plot into an interactive plotly plot using the ggplotly() function:

R
# Convert ggplot to plotly
p_plotly <- ggplotly(p)

p_plotly

Output:

gh
Convert to Plotly Using ggplotly()

Step 4: Remove the Option Bar

Now, use the config() function to remove the option bar by setting displayModeBar = FALSE:

R
# Remove the option bar using config
p_plotly <- ggplotly(p) %>%
    config(displayModeBar = FALSE)

# Show the plot
p_plotly

Output:

gh
Remove the Option Bar

The resulting plot will not have the toolbar displayed at the top.

Conclusion

Removing the option bar from a ggplotly plot in R is a simple and effective way to create cleaner visualizations. Whether you’re embedding the plot in a report or web application, removing unnecessary interface elements can enhance the overall look and usability of your visualizations. The config() function gives you full control over the display of interactive features like the mode bar, ensuring that your plot meets the design requirements of your project. By leveraging config(), you can customize the level of interactivity in your plotly visualizations, making them more suitable for presentations, reports, and professional visualizations.


Next Article

Similar Reads