Reputation: 829
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.
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()
Upvotes: 0
Views: 469
Reputation: 66425
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')
Upvotes: 1