[英]R Plotly - Add annotation to reference line in a scatter plot
我使用虹膜數據集在R中使用Plotly創建了一個散點圖,並添加了兩條參考線,一條在x軸上表示平均值Sepal.Width,另一條在y軸上表示平均值Sepal.Length。
以下是可執行的R代碼:
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
上面的R代碼產生以下Plotly輸出
我想為兩條參考線(“均值分隔寬度”和“均值分隔長度”)添加注釋文本(即標簽)。
我遇到過類似的帖子,但是那里提到的解決方案對我不起作用。 如果有人可以向我提供代碼的解決方案,那么將不勝感激。
PS:我正在使用Plotly版本4.8.0
以下代碼解決了我的問題。 希望它可以幫助某人。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.