简体   繁体   中英

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 eg

+ 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?

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM