0

How to manually set the labels of the points in a plotly?

library(ggplot2)
library(plotly)
p <- iris %>% 
 ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
 geom_point() +
 labs(
  title = "A graph",
  x = "Sepal Length (cm)",
  y = "Sepal Width (cm)",
  color = "Species of Iris"
) 

ggplotly(p)

The axis are correctly labelled, but the data is not. R output


Here is an example of how it works in Python

https://plotly.com/python/figure-labels/

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                 labels={
                     "sepal_length": "Sepal Length (cm)",
                     "sepal_width": "Sepal Width (cm)",
                     "species": "Species of Iris"
                 },
                title="Manually Specified Labels")
fig.show()

result of popups

2
  • You might check here: plotly.com/r/hover-text-and-formatting Commented Jun 15, 2022 at 22:19
  • None of these examples use ggplotly. They all build their plotly from scratch. Commented Jun 15, 2022 at 22:26

1 Answer 1

1

Here's an example using the text aesthetic that ggplot doesn't use, but which gets passed along to plotly, and glue::glue as an alternative to paste0.

library(ggplot2)
library(plotly)
p <- iris %>% 
  ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point(aes(text = glue::glue(
    "Species of iris={Species}\n",
    "Sepal Width (cm)={Sepal.Width}"))) +
  # alternative using base paste0:
  #geom_point(aes(text = paste0("Species of iris=", Species, "\n",
  #                             "Sepal Width (cm)=", Sepal.Width))) +
  labs(
    title = "A graph",
    x = "Sepal Length (cm)",
    y = "Sepal Width (cm)",
    color = "Species of Iris"
  ) 

ggplotly(p, tooltip = 'text')
  
Sign up to request clarification or add additional context in comments.

1 Comment

Oh that works! thanks, not the most elegant syntax, but it will do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.