Reputation: 311
I have created a scatterplot with Plotly in R using the iris dataset and have added two reference lines, one on the x-axis denoting the mean Sepal.Width and the other on the y-axis denoting the mean Sepal.Length.
Below is the executable R code:
library(dplyr)
library(plotly)
iris <- datasets::iris
scatterplot <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter',
text = ~Species,
color = I('orange')) %>%
layout(shapes=list(list(type = 'line',
x0 = mean(iris$Sepal.Width),
x1 = mean(iris$Sepal.Width),
y0 = 4,
y1 = 8,
line = list(width = 2)),
list(type = 'line',
x0 = 1.5,
x1 = 5,
y0 = mean(iris$Sepal.Length),
y1 = mean(iris$Sepal.Length),
line = list(width = 2))))
scatterplot
The above R code produces the following Plotly output
I want to add annotation text (i.e. label) for the two reference lines ("Mean Sepal Width" and "Mean Sepal Length").
I came across a similar post however the solution mentioned there did not work for me. If someone can provide me the solution with the code then that would be highly appreciated.
PS: I am using Plotly version 4.8.0
Upvotes: 0
Views: 1607
Reputation: 311
The following code solved my problem. Hope it helps someone.
library(dplyr)
library(plotly)
iris <- datasets::iris
scatter <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter',
text = ~Species,
color = I('orange')) %>%
layout(shapes=list(list(type = 'line',
x0 = mean(iris$Sepal.Width),
x1 = mean(iris$Sepal.Width),
y0 = 4,
y1 = 8,
line = list(width = 2)),
list(type = 'line',
x0 = 1.5,
x1 = 5,
y0 = mean(iris$Sepal.Length),
y1 = mean(iris$Sepal.Length),
line = list(width = 2))),
annotations = list(list(
x = 3.4,
y = 7.9,
xref = 'x',
yref = 'y',
text = 'Mean Sepal Width',
showarrow = FALSE
),
list(
x = 4.7,
y = 5.6,
xref = 'x',
yref = 'y',
text = 'Mean Sepal Length',
showarrow = FALSE
)))
scatter
Upvotes: 2