Search code examples
rggplot2plotlyggplotly

Modify legend of ggplotly plot - change legend title and items


I want to modify the legend of the following plot (minimal example):

library(ggplot2)
library(plotly)

data(iris)

plt <- ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) + 
  geom_point()

In particular, I need to modify the title and the item names (setosa, versicolor, virginica should be any other string I supply for each species).

In plain ggplot2 this is possible with e.g.

+ scale_color_discrete(name = "Flower Species",
                       labels = c("SET", "VERS", "VIRG"))

and this works fine by itself.

But these legend modifications are not adopted when converting the plot with ggplotly().

In the documentation of ggplotly I cannot find the modifications that I need.

  • How to modify the legend of a ggplotly plot?
  • If that is not possible, how to convert a ggplot plot into a plotly plot without ggplotly, and then to modify the legend of the standard plotly plot?

Solution

  • Based on this answer, you can edit the names of the value labels after creating the ggplotly object. I will admit that I don't like this solution and believe there should be a better way to do this, although some other ggplotly answers I found on SO no longer work.

    library(tidyverse)
    library(plotly)
    data(iris)
    
    plt <- ggplotly (
      ggplot(data = iris, aes(Sepal.Length, Sepal.Width, color = Species)) + 
      geom_point() + 
      scale_color_discrete(name = "Flower Species") 
      )
    
    plt$x$data[[1]]$name <- "SET"
    plt$x$data[[2]]$name <- "VERS"
    plt$x$data[[3]]$name <- "VIRG"
    plt
    

    enter image description here